Hex数组浮动

Enz*_*dal -2 c arrays hex

我有一个数组

unsigned char array_a[4] = {0x00,0x00,0x08,0x4D};
unsigned char val[4];
float test;
Run Code Online (Sandbox Code Playgroud)

我想要做的是组合所有元素并将其存储到val以使其为0x0000084D并将其转换为浮动,即2125.

我试过memcpy

 memcpy(val,array_a,4);
 val[4] = '\0';
Run Code Online (Sandbox Code Playgroud)

但仍然不行.

Jea*_*bre 5

首先,0x0000084D整数值 2125的大端表示,而不是IEEE float.

其次,不需要复制到另一个char数组(并且在尝试"nul-terminate"数组时访问第5个元素超出范围).那部分毫无意义.

要将此数组转换为主机上的整数,请先将其复制为标准的32位整数,然后根据计算机的字节顺序进行转换(否则您将在小端机器上获得错误的值)

  unsigned char array_a[4] = {0x00,0x00,0x08,0x4D};
  uint32_t the_int;
  memcpy(&the_int,array_a,sizeof(uint32_t));
  the_int = ntohl(the_int);

  printf("%d\n",the_int);
Run Code Online (Sandbox Code Playgroud)

或没有任何外部转换库使用位移使其与字节无关:

  uint32_t the_int = 0;
  int i;
  for (i=0;i<sizeof(uint32_t);i++)
  {
     the_int <<= 8;
     the_int += array_a[i];
  }
Run Code Online (Sandbox Code Playgroud)

你可以得到2125,如果你愿意,现在你可以把它分配给浮子

float test = the_int;
Run Code Online (Sandbox Code Playgroud)