gpt4 book ai didi

c - 字节到 C 中的 signed int

转载 作者:太空狗 更新时间:2023-10-29 15:55:37 29 4
gpt4 key购买 nike

我有一个二进制值存储在 C 中的一个 char 中,我想将这个字节转换为 C 中的有符号整数。目前我有这样的东西:

char a = 0xff;
int b = a;
printf("value of b: %d\n", b);

标准输出的结果将是“255”,期望的输出是“-1”。

最佳答案

根据C99标准,

6.3.1.3 Signed and unsigned integers

When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.


在分配给 int 之前,您需要将 char 转换为 signed char,作为任何值 char可以直接表示为 int

#include <stdio.h>

int main(void) {
char a = 0xff;
int b = (signed char) a;
printf("value of b: %d\n", b);
return 0;
}

快速测试表明它在这里工作:

C:\dev\scrap>gcc -std=c99 -oprint-b print-b.c

C:\dev\scrap>print-b
value of b: -1

请注意,C99 标准未定义 char 是否将其视为有符号或无符号。

6.2.5 Types

An object declared as type char is large enough to store any member of the basic execution character set. If a member of the basic execution character set is stored in a char object, its value is guaranteed to be positive. If any other character is stored in a char object, the resulting value is implementation-defined but shall be within the range of values that can be represented in that type.

...

The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char.

关于c - 字节到 C 中的 signed int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11819658/

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