How to convert 64 bit int to binary presentation (big endian)? For reverse task I use these functions:
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;
}
Serialising a 64 bit unsigned number into an array of unsigned char
, storing 8 bits in each in big-endian order, can be done like so:
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;
}
You shouldn't use built-in types for serialization; instead, when you need to know the exact size of a type, you need fixed-width types:
#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);
Similarly for 32-bit values, use uint32_t
there. Make sure your source buffer uses unsigned chars.
精彩评论