char arrays's

If I have an 8 bit integer which I want to insert into an character array I can do something like this

1
2
  char chararray[9];
  chararray[4] = 0xAF


what if I had a 64 bit integer that I wanted to push into that array at indices 5,6,7 and 8. I realize I could break it in to 4 chunks if the number was static. Of course it's not.

Also, is a character array the best way to store a stream of bits for easy access. So far it seems that way, but I am always looking for advice
A 64 bit value required 8 bytes, not 4. That aside, if your array was large enough, you could force one in using a cast.

The idea is this. A 64 bit integer has a particular bit pattern across 8 bytes. We can just copy that bit pattern in onto some specified memory location.

The cast example:
1
2
3
4
char array[32];
uint64_t n = 0x0123456789abcdef;

*((uint64_t*)(&array[5])) = n; // address of array[5] is really the address of a uint64_t 


memcpy example:
1
2
3
4
char array[32];
uint64_t n = 0x0123456789abcdef;

memcpy(&array[5], &n, sizeof(n));
Last edited on
yes sorry I misspoke I meant 32bit. however I believe memcopy will accomplish what I need. Thank you.
Topic archived. No new replies allowed.