How to convert a 64-bit int to a binary presentation?

How to convert a 64-bit int to a binary representation (large endian)? For the inverse problem, I use the following 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; } 
+4
source share
2 answers

Serialization of a 64-bit unsigned number into an array from unsigned char , storing 8 bits in each in a large order, can be performed as follows:

 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; } 
+3
source

You should not use built-in types for serialization; instead, when you need to know the exact type size, 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 . Make sure the source buffer uses unsigned characters.

+2
source

All Articles