How to get the value of individual bytes of a variable?

后端 未结 5 1170
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 06:06

I know that to get the number of bytes used by a variable type, you use sizeof(int) for instance. How do you get the value of the individual bytes used when you

5条回答
  •  我在风中等你
    2020-12-03 06:34

    You could make use of a union but keep in mind that the byte ordering is processor dependent and is called Endianness http://en.wikipedia.org/wiki/Endianness

    #include 
    #include 
    
    union my_int {
       int val;
       uint8_t bytes[sizeof(int)];
    };
    
    int main(int argc, char** argv) {
       union my_int mi;
       int idx;
    
       mi.val = 128;
    
       for (idx = 0; idx < sizeof(int); idx++)
            printf("byte %d = %hhu\n", idx, mi.bytes[idx]);
    
       return 0;
    }
    

提交回复
热议问题