I\'m trying to convert a struct to a char array to send over the network. However, I get some weird output from the char array when I do.
#include
Treating your struct as if it were a char array is undefined behavior. To send it over the network, use proper serialization instead. It's a pain in C++ and even more so in C, but it's the only way your app will work independently of the machines reading and writing.
http://en.wikipedia.org/wiki/Serialization#C
The signedness of char array is not the root of the problem! (It is -a- problem, but not the only problem.)
Alignment! That's the key word here. That's why you should NEVER try to treat structs like raw memory. Compliers (and various optimization flags), operating systems, and phases of the moon all do strange and exciting things to the actual location in memory of "adjacent" fields in a structure. For example, if you have a struct with a char followed by an int, the whole struct will be EIGHT bytes in memory -- the char, 3 blank, useless bytes, and then 4 bytes for the int. The machine likes to do things like this so structs can fit cleanly on pages of memory, and such like.
Take an introductory course to machine architecture at your local college. Meanwhile, serialize properly. Never treat structs like char arrays.
When you go to send it, just use:
(char*)&CustomPacket
to convert. Works for me.
The x
format specifier by itself says that the argument is an int
, and since the number is negative, printf
requires eight characters to show all four non-zero bytes of the int
-sized value. The 0
modifier tells to pad the output with zeros, and the 2
modifier says that the minimum output should be two characters long. As far as I can tell, printf
doesn't provide a way to specify a maximum width, except for strings.
Now then, you're only passing a char
, so bare x
tells the function to use the full int
that got passed instead — due to default argument promotion for "...
" parameters. Try the hh
modifier to tell the function to treat the argument as just a char
instead:
printf("%02hhx", b[i]);