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

后端 未结 10 2204
北荒
北荒 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:30

    The problem is arising as unsigned char is a 4 byte number not a 1 byte number as many think, so change it to

    union {
    unsigned int integer;
    char byte[4];
    } temp32bitint;
    

    and cast while printing, to prevent promoting to 'int' (which C does by default)

    printf("%u, %u \n", (unsigned char)Buffer[0], (unsigned char)Buffer[1]);
    

提交回复
热议问题