Problems converting chars, byte, strings?

Oct 4, 2009 at 3:31am
I want my unsigned chars to be written into a file using io streams and be readable like 00 03 ab 00 cc etc.
anyone have a simple solution or even a name for this kind of converting I've tried all night -.-,
I'm starting to get really tired.
Last edited on Oct 4, 2009 at 3:32am
Oct 4, 2009 at 6:27am
do you mean hexademical?
If yes, then you could try something like
1
2
3
4
5
6
const char number[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

unsigned char n1 = mychar >> 4; //to get the first four bits
unsigned char n2 = mychar & 0xF; //to get the last four bits

myfile<<number[n1]<<number[n2]<<' ';

I bet there is a shorter way to do this with standard libraries though.

Hope this helps
Oct 4, 2009 at 7:28am
iostreams can do hexadecimal. See here:

http://www.cplusplus.com/reference/iostream/manipulators/
Oct 4, 2009 at 10:32am
The thing is that it's network packages that i want to log sort of like the same way some packetanalyzers do it:

const unsigned char* bytes = static_cast<const unsigned char*>(packet->GetData());

I want every byte from the unsigned "bytes" to be put in a file separated by spaces.
So it will look something like this: 00 10 29 AA C8 E3 etc.

I don't only want the code i want to learn something as well so i would be pleased if someone described how it works.

Thank you hamsterman this was exactly what i was looking for!
Oct 4, 2009 at 11:45am
You'll just have to insert a space after every second character. There is no library routine to do that. If you also want uppercase letters you can use the uppercase stream manipulator with the hex manipulator...

Good luck!
Topic archived. No new replies allowed.