[ACCEPTED]-Convert array of 8 bytes to signed long in C++-long-integer

Accepted answer
Score: 10

You probably should use a int64_t which is guaranteeed 5 to be 8 bytes long.

You don't state how your 4 data is represented (its endianness) into 3 your array but you might use reinterpret_cast<> or even better: use 2 shift operations to "build" your integer.

Something 1 like:

unsigned char array[8] = { /* Some values here */ };
uint64_t value = 
  static_cast<uint64_t>(array[0]) |
  static_cast<uint64_t>(array[1]) << 8 |
  static_cast<uint64_t>(array[2]) << 16 |
  static_cast<uint64_t>(array[3]) << 24 |
  static_cast<uint64_t>(array[4]) << 32 |
  static_cast<uint64_t>(array[5]) << 40 |
  static_cast<uint64_t>(array[6]) << 48 |
  static_cast<uint64_t>(array[7]) << 56;
Score: 5

Another way of conversion between data types, which 6 I find convenient in some cases, is to use 5 the union data type, which allows you to 4 access the same memory portion as different 3 data types. Of course all other remarks 2 regarding endianness, size of data-types 1 etc. still hold.

For example:

union bytes {
    unsigned char c[8];
    uint64_t l;
} myb;
myb.c[0] = 0;
myb.c[1] = 1;
myb.c[2] = 0;
myb.c[3] = 0;
myb.c[4] = 0;
myb.c[5] = 0;
myb.c[6] = 0;
myb.c[7] = 0;
cout << "value of myb.l: " << myb.l << "\n";
Score: 1

Why not just something like the following?

uint8_t start_arr[8] = {0,1,2,3,4,5,6,7};
uint64_t val = (uint64_t)(*(uint64_t*)&start_arr[0]);
std::cout << std::hex << val << std::endl;

0

Score: 0

Some long integers are 8 bytes, some are 9 4. The 8 byte variant usually exists only 8 on 64-bit systems. Check this page if you want to 7 get an idea.

Of course, we don't know what 6 it is in your case, so you'd have to post 5 more details.

To be on the safe side, you 4 could decide to put the 8 bytes into 2 long 3 integers anyway. That way, it will always 2 work. In the worst case you'd be wasting 1 half your storage space.

Score: 0

Only C99 has types guaranteed to hold 64 4 bits of information - long long and int*64_t. For C++, you 3 should look for a BigInt class/library. Or, as 2 has been suggested, roll your own class 1 using two longs.

More Related questions