Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting byte array to double - c

Tags:

c

bytearray

I'm trying to get the numerical (double) value from a byte array of 16 elements, as follows:

unsigned char input[16];
double output;
...
double a  = input[0];
distance = a;
for (i=1;i<16;i++){
    a = input[i] << 8*i;
    output += a;
}

but it does not work. It seems that the temporary variable that contains the result of the left-shift can store only 32 bits, because after 4 shift operations of 8 bits it overflows.

I know that I can use something like

a = input[i] * pow(2,8*i);

but, for curiosity, I was wondering if there's any solution to this problem using the shift operator...

like image 910
paolo_ Avatar asked Aug 19 '09 17:08

paolo_


1 Answers

Edit: this won't work (see comment) without something like __int128.

a = input[i] << 8*i;

The expression input[i] is promoted to int (6.3.1.1) , which is 32bit on your machine. To overcome this issue, the lefthand operand has to be 64bit, like in

a = (1L * input[i]) << 8*i;

or

a = (long long unsigned) input[i] << 8*i;

and remember about endianness

like image 69
Adrian Panasiuk Avatar answered Sep 20 '22 20:09

Adrian Panasiuk