简体   繁体   中英

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

I'm not sure how to unlock characters past 255 automatically.

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

Results in 107 . No surprise.

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

Results in 95 . It seems this has been modulo divided by 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? I need to go past 255 for the sake of a hash function.

A char is a byte in memory. 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). When the value is more than 255, it overflows.

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).

You can use another type than char if you want to store values > 255.

A char data type is an 8-bit field, with a maximum total value of 255 . You need to use a 16-bit value if you wish to work with numbers greater than 255.

unsigned char has a value range of 0 to 255
signed char has a value range of -128 to 127

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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