Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store an int in a char array?

Tags:

I want to store a 4-byte int in a char array... such that the first 4 locations of the char array are the 4 bytes of the int.

Then, I want to pull the int back out of the array...

Also, bonus points if someone can give me code for doing this in a loop... IE writing like 8 ints into a 32 byte array.

int har = 0x01010101; char a[4]; int har2;  // write har into char such that: // a[0] == 0x01, a[1] == 0x01, a[2] == 0x01, a[3] == 0x01 etc.....  // then, pull the bytes out of the array such that: // har2 == har 

Thanks guys!

EDIT: Assume int are 4 bytes...

EDIT2: Please don't care about endianness... I will be worrying about endianness. I just want different ways to acheive the above in C/C++. Thanks

EDIT3: If you can't tell, I'm trying to write a serialization class on the low level... so I'm looking for different strategies to serialize some common data types.

like image 714
Polaris878 Avatar asked Oct 05 '09 23:10

Polaris878


1 Answers

Unless you care about byte order and such, memcpy will do the trick:

memcpy(a, &har, sizeof(har)); ... memcpy(&har2, a, sizeof(har2)); 

Of course, there's no guarantee that sizeof(int)==4 on any particular implementation (and there are real-world implementations for which this is in fact false).

Writing a loop should be trivial from here.

like image 132
Pavel Minaev Avatar answered Oct 11 '22 06:10

Pavel Minaev