如何从四个复合字节中构建一个32位浮点数,这难道不是个神奇的过程吗?

2026-04-16 22:163阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计303个文字,预计阅读时间需要2分钟。

如何从四个复合字节中构建一个32位浮点数,这难道不是个神奇的过程吗?

我正在尝试构建一个32位浮点数,使用以下复合字节数结构。有没有比以下方法更优(或更方便)的实现方式?

pythonfloat_number=( (0x00 <<24) | # sign bit (0x7F << 23) | # exponent bits (0x40 << 8) | # fraction bits 0x00 # trailing zeros)

我正在尝试用4个复合字节构建一个32位浮点数.有没有比使用以下方法更好(或更便携)的方法?

如何从四个复合字节中构建一个32位浮点数,这难道不是个神奇的过程吗?

#include <iostream> typedef unsigned char uchar; float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3) { float output; *((uchar*)(&output) + 3) = b0; *((uchar*)(&output) + 2) = b1; *((uchar*)(&output) + 1) = b2; *((uchar*)(&output) + 0) = b3; return output; } int main() { std::cout << bytesToFloat(0x3e, 0xaa, 0xaa, 0xab) << std::endl; // 1.0 / 3.0 std::cout << bytesToFloat(0x7f, 0x7f, 0xff, 0xff) << std::endl; // 3.4028234 × 10^38 (max single precision) return 0; } 你可以使用memcpy( Result)

float f; uchar b[] = {b3, b2, b1, b0}; memcpy(&f, &b, sizeof(f)); return f;

或工会*(Result)

union { float f; uchar b[4]; } u; u.b[3] = b0; u.b[2] = b1; u.b[1] = b2; u.b[0] = b3; return u.f;

但这并不比你的代码更便携,因为不能保证平台是little-endian或浮点数是使用IEEE binary32甚至sizeof(float)== 4.

(注*:如@James所述,技术上不允许在标准(C§[class.union] / 1)中访问工会成员u.f.)

本文共计303个文字,预计阅读时间需要2分钟。

如何从四个复合字节中构建一个32位浮点数,这难道不是个神奇的过程吗?

我正在尝试构建一个32位浮点数,使用以下复合字节数结构。有没有比以下方法更优(或更方便)的实现方式?

pythonfloat_number=( (0x00 <<24) | # sign bit (0x7F << 23) | # exponent bits (0x40 << 8) | # fraction bits 0x00 # trailing zeros)

我正在尝试用4个复合字节构建一个32位浮点数.有没有比使用以下方法更好(或更便携)的方法?

如何从四个复合字节中构建一个32位浮点数,这难道不是个神奇的过程吗?

#include <iostream> typedef unsigned char uchar; float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3) { float output; *((uchar*)(&output) + 3) = b0; *((uchar*)(&output) + 2) = b1; *((uchar*)(&output) + 1) = b2; *((uchar*)(&output) + 0) = b3; return output; } int main() { std::cout << bytesToFloat(0x3e, 0xaa, 0xaa, 0xab) << std::endl; // 1.0 / 3.0 std::cout << bytesToFloat(0x7f, 0x7f, 0xff, 0xff) << std::endl; // 3.4028234 × 10^38 (max single precision) return 0; } 你可以使用memcpy( Result)

float f; uchar b[] = {b3, b2, b1, b0}; memcpy(&f, &b, sizeof(f)); return f;

或工会*(Result)

union { float f; uchar b[4]; } u; u.b[3] = b0; u.b[2] = b1; u.b[1] = b2; u.b[0] = b3; return u.f;

但这并不比你的代码更便携,因为不能保证平台是little-endian或浮点数是使用IEEE binary32甚至sizeof(float)== 4.

(注*:如@James所述,技术上不允许在标准(C§[class.union] / 1)中访问工会成员u.f.)