Converting an int into a 4 byte char array (C)

后端 未结 10 2197
北荒
北荒 2020-11-27 10:07

Hey, I\'m looking to convert a int that is inputed by the user into 4 bytes, that I am assigning to a character array. How can this be done?

Example:

Convert

10条回答
  •  悲&欢浪女
    2020-11-27 10:51

    Do you want to address the individual bytes of a 32-bit int? One possible method is a union:

    union
    {
        unsigned int integer;
        unsigned char byte[4];
    } foo;
    
    int main()
    {
        foo.integer = 123456789;
        printf("%u %u %u %u\n", foo.byte[3], foo.byte[2], foo.byte[1], foo.byte[0]);
    }
    

    Note: corrected the printf to reflect unsigned values.

提交回复
热议问题