Array to string
I cant seem to find a reasonable answer to my question through search so i thought i would post a new topic.
I have an array:
i need to convert the entire array to Hexadecimal.
My first thoughts to the appraoch was to convert the array to a string then strcmp but i cant seem to find how to connvert an array to a string either.
so my question is can you tell me how to convert the array to hexadecimal directly? or, How to convert the array to a string to be strcmp'ed?
Thanks in advance
So what is your string supposed to look like, when you've converted it?
"0x00, 0x01, 0x01, 0x00"
Or whatever endless variation you can imagine.
Perhaps start with sprintf() and the %x format.
The output would be the hexadecimal value for example if the array consists of 1,0,1,1 then the output should be B.
A simple for loop, multiplying each digit by a corresponding power of two and adding up in base 16 (hex) would do the trick.
Thanks Grumpy however im not sure i know what you mean...."multiplying each digit " by this do you mean each array element? if so then this is not what i require. i require the entire array, so 1011, to be converted to hex. Not just a single element.
Does that make sense? Am i misunderstanding your recommendation?
Yes, you have misunderstood. The words "simple for loop" in my previous post expressed one possible mechanism of looping over elements.
1011 in base 2 is equivalent to 1*8 + 0*4 + 1*2 + 1*1 which, in base 16, has value B. The values 8,4,2,1 are powers of 2. Work out a way to express that in a loop, that accesses the values (1's and 0's) in your array.
Essentially, all you're asking for is converting a binary (base 2) representation to hex (base 16).
Anything that can be printed by a sequence of printf's can also be combined into a string using sprintf. Here is one way to do it:
Originally Posted by weez
Suppose you can print this sequence
Then to put it in a string instead, do this:
The destination result must have enough room, and each of the sprintf calls must return no error.
char *s = result;
s += sprintf(s, "Hello");
s += sprintf(s, ", ");
s += sprintf(s, "World");
s += sprintf(s, "!!");