Store an int in a char array?

后端 未结 10 1628
攒了一身酷
攒了一身酷 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:57

    Note: Accessing a union through an element that wasn't the last one assigned to is undefined behavior. (assuming a platform where characters are 8bits and ints are 4 bytes) A bit mask of 0xFF will mask off one character so

    char arr[4];
    int a = 5;
    
    arr[3] = a & 0xff;
    arr[2] = (a & 0xff00) >>8;
    arr[1] = (a & 0xff0000) >>16;
    arr[0] = (a & 0xff000000)>>24;
    

    would make arr[0] hold the most significant byte and arr[3] hold the least.

    edit:Just so you understand the trick & is bit wise 'and' where as && is logical 'and'. Thanks to the comments about the forgotten shift.

提交回复
热议问题