How to convert a 48-bit byte array to a 64-bit integer in C?

I have an unsigned char array whose size is 6. The contents of the byte array is an integer (4096 * seconds since Unix Time). I know that the byte array is big-endian.

Is there a library in C that I can use to convert this byte array to int_64, or do I need to do this manually?

Thank!

PS: just in case, you need more information, yes, I'm trying to parse the Unix timestamp. Here is the specification of the timestamp format I'm dealing with.

+4
source share
5 answers

C99 uint64_t ( , , 64 ), :

#include <stdint.h>

unsigned char data[6] = { /* bytes from somewhere */ };
uint64_t result = ((uint64_t)data[0] << 40) |
                  ((uint64_t)data[1] << 32) |
                  ((uint64_t)data[2] << 24) |
                  ((uint64_t)data[3] << 16) |
                  ((uint64_t)data[4] << 8)  |
                  ((uint64_t)data[5] << 0);

C99 uint64_t, unsigned long long ( ) uint_least64_t. .

+8

:

unsigned char a [] = {0xaa,0xbb,0xcc,0xdd,0xee,0xff};
unsigned long long b = 0;
memcpy(&b,a,sizeof(a)*sizeof(char));
cout << hex << b << endl;

, , .

( ) , , , .

0

, - .

union time_u{
    uint8_t data[6];
    uint64_t timestamp;
}

uint64_t,

union time_u var_name;
var_name.data[i]
var_name.timestamp
0

64 :

uint64_t
convert_48_to_64(uint8_t *val_ptr){
  uint64_t ret = 0;
  uint8_t *ret_ptr = (uint8_t *)&ret;

  for (int i = 0; i < 6; i++) {
      ret_ptr[5-i] = val_ptr[i];
  }
  return ret;
 }

 convert_48_to_64((uint8_t)&temp);  //temp is in 48 bit

: num_in_48_bit = 77340723707904; 48- : 0100 0110 0101 0111 0100 1010 0101 1101 0000 0000 0000 0000 64- : 0000 0000 0000 0000 0000 0000 0000 0000 0101 1101 0100 1010 0101 0111 0100 0110 , val_ptr num_in_48_bit. uint8_t, val_ptr . . , .

0

#pragma pack(1)

__attribute__((packed))

typedef struct __attribute__((packed))
{
    uint64_t u48: 48;
} uint48_t;

uint48_t data;

memcpy(six_byte_array, &data, 6);
uint64_t result = data.u48;

-1
source

All Articles