Store an int in a char array?

后端 未结 10 1640
攒了一身酷
攒了一身酷 2020-11-27 17:24

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 o

10条回答
  •  悲哀的现实
    2020-11-27 17:53

    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.

提交回复
热议问题