将数字转换为字节数组

时间:2011-12-02 07:46:56

标签: c

嗨我有一个基数为10的数字,例如3198,十六进制表示为0x0C7E

如何将该数字转换为十六进制并将该十六进制值以[00] [0C] [7E]的格式放入字节数组中,假设我可以拥有的最大十六进制值为0xffffff。

3 个答案:

答案 0 :(得分:8)

也许这会有用吗?

uint32_t x = 0x0C7E;
uint8_t bytes[3];

bytes[0] = (x >> 0)  & 0xFF;
bytes[1] = (x >> 8)  & 0xFF;
bytes[2] = (x >> 16) & 0xFF;


/* Go back. */
x = (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0] << 0);

答案 1 :(得分:1)

Number已经是一个连续的内存块 - 无需将其转换为 ANOTHER 数组!只需使用指针算法获取单独的字节:

编辑:编辑为与字节无关的

#define FAST_ABS(x) ((x ^ (x>>31)) - (x>>31))

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } bint = {0x01020304};

    return bint.c[0] == 1; 
}    

uint32_t num = 0xAABBCCDD;
uint32_t N = is_big_endian() * 3;

printf("first byte 0x%02X\n"
       "second byte 0x%02X\n"
       "third byte 0x%02X\n"
       "fourth byte 0x%02X\n",
       ((unsigned char *) &num)[FAST_ABS(3 - N)],
      ((unsigned char *) &num)[FAST_ABS(2 - N)],
      ((unsigned char *) &num)[FAST_ABS(1 - N)],
      ((unsigned char *) &num)[FAST_ABS(0 - N)]
       );

答案 2 :(得分:0)

#include <stdio.h>

union uint32_value {
    unsigned int value;

    struct little_endian {
        unsigned char fou;
        unsigned char thi;
        unsigned char sec;
        unsigned char fir;
    } le;

    struct big_endian {
        unsigned char fir;
        unsigned char sec;
        unsigned char thi;
        unsigned char fou;
    } be;
};

int main(void)
{
    union uint32_value foo;
    foo.value = 3198;
    printf("%02x %02x %02x %02x\n", foo.le.fir, foo.le.sec, foo.le.thi, foo.le.fou);

    return 0;
}