C - 如何将int转换为uint8_t?

时间:2016-01-11 01:47:22

标签: c integer endianness

我有这个结构:

struct block{
    uint8_t *tBlock;
}

此结构将具有1024个字节,因此tBlock = malloc(1024)

我有一个整数,我想用4个字节写,所以tBlock [0]到tBlock [3]的小端。我有这个:

uint8_t little[4];

void inttolitend(uint32_t x, uint8_t* lit_int){
   lit_int[3] = (uint8_t)x / (256*256*256);
   lit_int[2] = (uint8_t)(x % (256*256*256)) / (256*256);
   lit_int[1] = (uint8_t)((x % (256*256*256)) % (256*256)) / 256;
   lit_int[0] = (uint8_t)((x % (256*256*256)) % (256*256)) % 256;
}

但是当我这样做时:

int x = 7;
inttolitend(x, little);

我得到的小[0] = 7,小[1] = 0,小[2] = 0和小[3] = 0所以我完全失败了我的转换器。我怎么能用4个字节的uint8_t得到7?

3 个答案:

答案 0 :(得分:4)

这是标准的方法 - 简洁明了:

void inttolitend(uint32_t x, uint8_t *lit_int) {
    lit_int[0] = (uint8_t)(x >>  0);
    lit_int[1] = (uint8_t)(x >>  8);
    lit_int[2] = (uint8_t)(x >> 16);
    lit_int[3] = (uint8_t)(x >> 24);
}

或使用类似于您的问题的算术:

void inttolitend(uint32_t x, uint8_t *lit_int) {
    lit_int[0] = (uint8_t)(x % 256);
    lit_int[1] = (uint8_t)(x / 256 % 256);
    lit_int[2] = (uint8_t)(x / 256 / 256 % 256);
    lit_int[3] = (uint8_t)(x / 256 / 256 / 256 % 256);
}

附录:

逆向转换 - 惯用语:

uint32_t litendtoint(uint8_t *lit_int) {
    return (uint32_t)lit_int[0] <<  0
         | (uint32_t)lit_int[1] <<  8
         | (uint32_t)lit_int[2] << 16
         | (uint32_t)lit_int[3] << 24;
}

或使用类似于您的问题的算术:

uint32_t litendtoint(uint8_t *lit_int) {
    return (uint32_t)lit_int[0]
         + (uint32_t)lit_int[1] * 256
         + (uint32_t)lit_int[2] * 256 * 256
         + (uint32_t)lit_int[3] * 256 * 256 * 256;
}

答案 1 :(得分:3)

void inttolitend(uint32_t x, uint8_t* lit_int){

    lit_int[0] = x & 0xff;
    lit_int[1] = (x>> 8) & 0xff;
    lit_int[2] = (x>> 16) & 0xff;
    lit_int[3] = (x>> 24) & 0xff;
}
  

我得到的很少[0] = 7,很少[1] = 0,很少[2] = 0而且很少[3] = 0

顺便说一下,这个 Little Endian for 7。

答案 2 :(得分:2)

OP使用lit_int[3] = (uint8_t)x / (256*256*256);错误地在分裂前做了演员。

void inttolitend(uint32_t x, uint8_t* lit_int){
   lit_int[3] = (uint8_t) (x / 16777216);
   lit_int[2] = (uint8_t) (x / 65536);
   lit_int[1] = (uint8_t) (x / 256);
   lit_int[0] = (uint8_t) x;
}

如果int x = 7; inttolitend(x, little);int不同,则调用int32_t会出现问题。

256*256*256在16位系统上溢出。