This question already has answers here:
Unions and type-punning

(5个答案)



Is type-punning through a union unspecified in C99, and has it become specified in C11?

(4个答案)


3年前关闭。




我想知道是否可以使用联合从接收到的char数组中获取浮点数。假设我已经定义了以下结构
typedef union {
  float f;
  char c[4];
} my_unionFloat_t;

如果我收到一个编码这样的浮点数的char数组(数字组成)
data[4] = {32,45,56,88};

我可以做以下事情吗?
my_unionFloat_t c2f;

c2f.c[0] = data[0];
c2f.c[1] = data[1];
c2f.c[2] = data[2];
c2f.c[3] = data[3];

float result = c2f.f;

最佳答案

在C++中最简单的方法是使用reinterpret_cast:

unsigned char data[4] = {32,45,56,88};
float f = reinterpret_cast<const float&>(data);
const unsigned char* ch =  reinterpret_cast<const unsigned char*>(&f);
for(int i=0; i<4; ++i)
    std::cout << +ch[i] << ' ';
std::cout << f << '\n';

关于c++ - union 可以用于将char数组转换为float吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43788955/

10-11 00:12