user1553386
user1553386

Reputation: 143

Not simple, converting long long from a char[8]

I got an array of char with 8 positions(char data[8];), this array has an unsigned long long int value on it (8 bytes of size)... data[0] has the first byte of the long long int, data[1] has the second and so on. My question is how to put that value again on an unsigned long long variable?

I've tried shifts but the value wasn't equal de original value, how can i do this without changing the original array...

The order of the bytes is little endian the normal order of variables (from Hight bit to low bit)

Here is a code that prints a different value than expected.

char vec[8]={0,0,0,0,0,0,0,1};

unsigned long long value = *((unsigned long long*) vec);

std::cout<<value;

return 0;

The result should be one but instead is 72057594037927936. Thank you for your patience.

Upvotes: 2

Views: 1576

Answers (4)

nhahtdh
nhahtdh

Reputation: 56829

You can do:

unsigned long long value = *((unsigned long long*) data);

But this assumes that:

  1. data is properly aligned to be accessed as a long long. For example, if long long requires 8-byte alignment but data is only 4-byte aligned, it can Do Bad Things.
  2. The bytes of data are stored in the same order as the current machine's byte order for long long. See Endianness.

Upvotes: 1

perreal
perreal

Reputation: 98118

Direct cast may not work depending on the hardware representation, this should work in most cases:

long long to_llong(unsigned char *data) {
    long long v = 0;
    for (int i = 0; i < 8; i++) {
      v = (v << 8) | data[i];
    }
    return v;
}

Upvotes: 1

Gang YIN
Gang YIN

Reputation: 2567

What do you mean by saying the first byte? It's the least significant byte or the most significant byte?

The answer to that question decides whether the number value is little-endian or big-endian. wikipedia link

If the value's endian style is the same with your system, you can just directly cast the address of the first byte to "unsigned long long *", while you will have to convert its endian style if it's no the same.

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320797

Assuming the byte order of your data array is the same as the resultant long long value

unsigned long long ll;
assert(sizeof ll == sizeof data);
memcpy(&ll, data, sizeof ll);

Avoid cast-based solutions. They violate strict-aliasing semantics and, for that reason, not guaranteed to work.

Upvotes: 4

Related Questions