gpt4 book ai didi

c++ - 应该将 float 转换为字节数组的程序中的运行时错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:04:21 24 4
gpt4 key购买 nike

我得到了一个浮点变量,想知道它的字节表示是什么。所以我去了IDEOne和wrote a simple program这样做。然而,令我惊讶的是,它会导致运行时错误:

#include <stdio.h>
#include <assert.h>

int main()
{
// These are their sizes here. So just to prove it.
assert(sizeof(char) == 1);
assert(sizeof(short) == 2);
assert(sizeof(float) == 4);

// Little endian
union {
short s;
char c[2];
} endian;
endian.s = 0x00FF; // would be stored as FF 00 on little
assert((char)endian.c[0] == (char)0xFF);
assert((char)endian.c[1] == (char)0x00);

union {
float f;
char c[4];
} var;
var.f = 0.0003401360590942204;
printf("%x %x %x %x", var.c[3], var.c[2], var.c[1], var.c[0]); // little endian
}

在 IDEOne 上,它输出:

39 ffffffb2 54 4a

以及运行时错误。为什么会出现运行时错误,为什么 b2 实际上是 ffffffb2?我对 b2 的猜测是符号扩展。

最佳答案

char是有符号类型。如果它是 8 位长,而你在其中放入任何大于 127 的东西,它就会溢出。有符号整数溢出是未定义的行为,因此使用期望无符号值的转换说明符打印有符号值( %x 期望 unsigned int ,但是 char 在传递给可变参数时被提升 [隐式转换] 为 signed int printf() 函数)。

底线 - 更改 char c[4]unsigned char c[4]它将正常工作。

关于c++ - 应该将 float 转换为字节数组的程序中的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17868589/

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