简体   繁体   English

C - 为什么向字符添加数字会重置为 255?

[英]C - Why does adding numbers to a char reset at 255?

I'm not sure how to unlock characters past 255 automatically.我不确定如何自动解锁超过 255 个字符。

char f;
f = 'k';
printf("%d\n", f);

Results in 107 .结果在107 No surprise.没有惊喜。

f += 500;
printf("%d\n", f);

Results in 95 .结果在95 It seems this has been modulo divided by 255.似乎这已被模除以 255。

printf("%c\n", 607);

Results in _ .结果在_ There are many more characters that extend into the thousands as well.还有更多的字符可以扩展到数千个。 How come adding a value and making a char go past 255 forces a modulo operation?为什么添加一个值并使 char 超过 255 会强制进行模运算? I need to go past 255 for the sake of a hash function.为了哈希函数,我需要超过 255。

A char is a byte in memory. char是内存中的一个字节。 So you can not store values > 255 because it has only 8 bits (assuming that on your platform a char is defined as a byte of 8 bits).所以你不能存储大于 255 的值,因为它只有 8 位(假设在你的平台上一个 char 被定义为一个 8 位的字节)。 When the value is more than 255, it overflows.当该值大于 255 时,它会溢出。

Furthermore, you don't know if a char is unsigned (values can be between 0 and 255) or signed (values can be between -128 and 127).此外,您不知道char是无符号的(值可以在 0 到 255 之间)还是有符号的(值可以在 -128 到 127 之间)。

You can use another type than char if you want to store values > 255.如果要存储大于 255 的值,可以使用char以外的其他类型。

A char data type is an 8-bit field, with a maximum total value of 255 . char数据类型是一个8-bit字段,最大值为255 You need to use a 16-bit value if you wish to work with numbers greater than 255.如果您希望处理大于 255 的数字,则需要使用16-bit值。

unsigned char has a value range of 0 to 255 unsigned char的值范围为0 to 255
signed char has a value range of -128 to 127 signed char的值范围为-128 to 127

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM