gpt4 book ai didi

c++ - 通过取消引用字节数组的指针来赋值是错误的吗?

转载 作者:太空狗 更新时间:2023-10-29 23:50:44 24 4
gpt4 key购买 nike

我有一个代码,我在其中取消引用字节数组指针并将值分配给变量。这适用于 int 和 bool,但不适用于 float 和 double 类型。所以我认为我面临一个普遍的问题。我做了一个样本:

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>

using namespace std;
typedef unsigned char Byte;

int main( )
{
vector<Byte> v(10);
float f1 = 14.6;
copy_n((Byte*)&f1, sizeof(float), (Byte*)&v[4]);

float f2 = v[4];
float f3 = 0;
copy_n((Byte*)&v[4], sizeof(float), (Byte*)&f3);
cout << "f2: " << f2 << " f3: " << f3 << endl;

return 0;
}

std::copy_n 按预期工作,所以我必须使用它而不是 f2 = v[4]

output: f2: 154 f3: 14.6

f2 = v[4] 构造有什么问题?

最佳答案

使用 float f2 = v[4] 会发生什么:float f2 = (float) v[4] 其中 v[4] 是一个 Byte 又名 unsigned char。您获取该元素(仅该元素)并将其转换为 float 。

In v[4] you have the least significant byte of f1,
...
In v[7] you have the most significant byte of f1

它们是相反的,因为您的系统是小端。

使用 int 它可以工作,因为您使用了一个小于 128 的值,并且因为系统是小尾数法。即 v[4] 保存原始 f1 的最低有效字节。与 float 一样,您忽略其他 3 个字节,但在这种情况下(小于 128 的 int)其余字节为 0,因此您看不到任何危害。

关于c++ - 通过取消引用字节数组的指针来赋值是错误的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27675030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com