c语言float和bytes array转换

楚天乐 1918 0 条

重点:大小端不要搞错

  1. x86是小端,0x123456,对应4个字节,0x12,0x34,0x56,0x78. 在内存中的存储顺序是 0x78, 0x56, 0x34, 0x12
#include <stdio.h>

int main(){
    unsigned char buffer[] = {0x46, 0x87, 0x92, 0x64};
    float a = 17353.195f;
    float b = 0;

    printf("zzzzz ....\n");

    unsigned int* pa = (unsigned int*)(&a);

    unsigned int x = *pa;
    int x1 = (x >> 24) & 0xFF;
    int x2 = (x >> 16) & 0xFF;
    int x3 = (x >> 8) & 0xFF;
    int x4 = x  & 0xFF;

    printf("%x",x1 );
    printf("%x", x2);
    printf("%x", x3);
    printf("%x", x4);
    printf("\n");

    unsigned char* pb = (unsigned char*)(&b);

    // 重点!
    *pb = buffer[3];
    *(pb+1) = buffer[2];
    *(pb+2) = buffer[1];
    *(pb+3) = buffer[0];

    printf("%.8f\n", b);
    return 1;
}

输出

46879264
17353.19531250


与本文相关的文章

发表我的评论
昵称 (必填)
邮箱 (必填)
网址
执行时间: 1716578915853.7 毫秒