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

后端 未结 10 2131
北荒
北荒 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:33
    int a = 1;
    char * c = (char*)(&a); //In C++ should be intermediate cst to void*
    
    0 讨论(0)
  • 2020-11-27 10:34

    The issue with the conversion (the reason it's giving you a ffffff at the end) is because your hex integer (that you are using the & binary operator with) is interpreted as being signed. Cast it to an unsigned integer, and you'll be fine.

    0 讨论(0)
  • 2020-11-27 10:38

    You can simply use memcpy as follows:

    unsigned int value = 255;
    char bytes[4] = {0, 0, 0, 0};
    memcpy(bytes, &value, 4);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题