I have byte array like aa,bb,12,77
I want to convert it to char* so when I do
Printf("%s",newCharPtr);
I will get aabb1277
How can I do it please?
I have byte array like aa,bb,12,77
I want to convert it to char* so when I do
Printf("%s",newCharPtr);
I will get aabb1277
How can I do it please?
Do you reeeeeeeeeeeeeeeeeeeally want a string, or do you just want to print it in hex?
Either way I would suggest using the %x specifier for printf in a loop (either printf to the screen or sprintf to make a string); if you're planning to make a string out of it, you will need more space allocated, because the byte aa and the string "aa" aren't compatible with each other.
Sounds like you're going to be using sprintf[fn 1] in a loop, then. (Note that while "bigger" is important, so is "different" -- you won't be able to use the same memory for both.) You will probably want to use %0x so that leading zeroes get printed into your string; you'll have to move forward two spaces in your string buffer at a time, since you'll be printing two characters at a time; you'll need to make sure there's a \0 at the end. You can malloc exactly the right amount of space at the beginning, since you know you'll need 2n+1 bytes to store the string.
[fn 1]If for some reason you're going to be doing this a zillion times and you don't want to call sprintf all that time, or you just think it would impress people, you can try to use a hash-table of characters and use the byte (or some bit-masked version of the byte) as an index to grab each character/pair of characters and copy them into your buffer. I don't know that I would start there, though.
EDIT: Sitting down with a piece of paper, the hash-table method isn't as complicated as I had originally thought, so maybe you could start there after all.
Last edited by tabstop; 11-01-2018 at 03:58 PM.
Code:#include <stdio.h> #include <stdlib.h> int main() { unsigned char a[] = {0xab,0xcd,0xef,0x0f,0x0e,0x0d,0x0c}; char *s = malloc(sizeof a * 2 + 1); for (size_t i = 0; i < sizeof a; i++) sprintf(s + i * 2, "%02x", a[i]); printf("%s\n",s); free(s); return 0; }
Last edited by john.c; 11-01-2018 at 04:45 PM.
A little inaccuracy saves tons of explanation. - H.H. Munro
Hi!
I'am new here. My Nickname should be rustyoldguy. Sorry my failure. Now to you.
I think you can use also this here:
Code:#include <stdio.h> #include <stdlib.h> int main() { char hexvalue[100]; union xval { unsigned char ubytearray[4]; unsigned int icompval; } xhex; xhex.ubytearray[0] = 0x77; xhex.ubytearray[1] = 0x12; xhex.ubytearray[2] = 0xbb; xhex.ubytearray[3] = 0xaa; printf("Value as decimal: %u as hex:%x\n", xhex.icompval, xhex.icompval); sprintf(hexvalue, "%x", xhex.icompval); printf("as string: %s\n", hexvalue); return 0; }
Due to endianness, you can't be sure what order those bytes will print on a particular system (so it's not portable). Also, you presumably want to say "%08x".
A little inaccuracy saves tons of explanation. - H.H. Munro