如何将64位int转换为二进制表示?

时间:2011-08-17 21:27:07

标签: c

如何将64位int转换为二进制表示(big endian)?对于反向任务,我使用以下函数:

int readInt (struct str *buf) {
    buf -> cur_len = buf -> cur_len + 4;
    return 
    (((buf -> data[buf -> cur_len - 3 ] & 0xff) << 24) | 
    ((buf -> data[buf -> cur_len - 2 ] & 0xff) << 16) |
    ((buf -> data[buf -> cur_len - 1 ] & 0xff) <<  8) |
    ((buf -> data[buf -> cur_len ] & 0xff) <<  0));
};


long unsigned int 32Bit(struct str *buf) {  // 32
    return ((long unsigned int)readInt(buf)) & 0xffffffffL;
};

long unsigned int 64Bit(struct str *buffer) { //64
    long unsigned int result = 32Bit(buf);
    result *= 4294967296.0;
    return result;
}

2 个答案:

答案 0 :(得分:3)

将64位无符号数序列化为unsigned char数组,以big-endian顺序存储8位,可以这样完成:

void serialise_64bit(unsigned char dest[8], unsigned long long n)
{
    dest[0] = (n >> 56) & 0xff;
    dest[1] = (n >> 48) & 0xff;
    dest[2] = (n >> 40) & 0xff;
    dest[3] = (n >> 32) & 0xff;
    dest[4] = (n >> 24) & 0xff;
    dest[5] = (n >> 16) & 0xff;
    dest[6] = (n >>  8) & 0xff;
    dest[7] = (n >>  0) & 0xff;
}

答案 1 :(得分:2)

您不应该使用内置类型进行序列化;相反,当您需要知道类型的确切大小时,您需要固定宽度类型:

#include <stdint.h>

unsigned char buf[8]; // 64-bit raw data

uint64_t little_endian_value =
   (uint64_t)buf[0] + ((uint64_t)buf[1] << 8) + ((uint64_t)buf[2] << 16) + ... + ((uint64_t)buf[7] << 56);

uint64_t big_endian_value =
   (uint64_t)buf[7] + ((uint64_t)buf[6] << 8) + ((uint64_t)buf[5] << 16) + ... + ((uint64_t)buf[0] << 56);

对于32位值,请在那里使用uint32_t。确保源缓冲区使用 unsigned 字符。