0

尝试将对齐的数组转换uint8[8]double. 使用位操作转换为特别容易,但我知道uint8[4]就符号位而言可能会变得混乱?longdouble

在Java中我只是使用ByteBuffer.wrap(bytes).getDouble(),但我认为它在C中并不容易。

我试图实现这段代码,但最后一个命令给出了错误Expression is not assignable并且Shift count >= width of type

long tempHigh = 0; 
long tempLow = 0;
double sum = 0;
tempHigh |= buffer[0] & 0xFF;
tempHigh <<= 8;
tempHigh |= buffer[1] & 0xFF;
tempHigh <<= 8;
tempHigh |= buffer[2] & 0xFF;
tempHigh <<= 8;
tempHigh |= buffer[3] & 0xFF;

tempLow |= buffer[4] & 0xFF;
tempLow <<= 8;
tempLow |= buffer[5] & 0xFF;
tempLow <<= 8;
tempLow |= buffer[6] & 0xFF;
tempLow <<= 8;
tempLow |= buffer[7] & 0xFF;

sum |= ((tempHigh & 0xFFFF) <<= 32) + (tempLow & 0xFFFF);

如何正确完成此过程仅解决我犯的错误?

提前致谢。

4

3 回答 3

3

double是浮点类型;它不支持按位运算,例如|.

您可以执行以下操作:

double sum;

memcpy(&sum, buffer, sizeof(sum));

但请注意字节顺序问题。

于 2012-05-02T13:48:25.037 回答
2

可移植的方法是使用按位算术将符号、指数和尾数值读出到整数变量中,然后调用ldexp以应用指数。

好的,这里有一些代码。请注意,它可能有不匹配的括号或一对一的错误。

unsigned char x[8]; // your input; code assumes little endian
long mantissa = ((((((x[6]%16)*256 + x[5])*256 + x[4])*256 + x[3])*256 + x[2])*256 + x[1])*256 + x[0];
int exp = x[7]%128*16 + x[6]/16 - 1023;
int sign = 1-x[7]/128*2;
double y = sign*ldexp(0x1p53 + mantissa, exp-53);
于 2012-05-02T17:38:45.527 回答
2

工会怎么样?像你一样写长部分,然后双精度自动正确。像这样的东西:

union 
{
   double sum;
   struct
   {
       long tempHigh;
       long tempLow;
   }v;
 }u;

 u.v.tempHigh = 0; 
 u.v.tempHigh |= buffer[0] & 0xFF;
 u.v.tempHigh <<= 8;
 u.v.tempHigh |= buffer[1] & 0xFF;
 u.v.tempHigh <<= 8;
 u.v.tempHigh |= buffer[2] & 0xFF;
 u.v.tempHigh <<= 8;
 u.v.tempHigh |= buffer[3] & 0xFF;

 u.v.tempLow |= buffer[4] & 0xFF;
 u.v.tempLow <<= 8;
 u.v.tempLow |= buffer[5] & 0xFF;
 u.v.tempLow <<= 8;
 u.v.tempLow |= buffer[6] & 0xFF;
 u.v.tempLow <<= 8;
 u.v.tempLow |= buffer[7] & 0xFF;

 printf("%f", u.sum);
于 2012-05-02T14:18:41.837 回答