简体   繁体   中英

Truncating of digits

I was going through the following code. It basically truncates the the digits of the character entered through cin object. The problem is I don't know how assigning an int value to a character object truncates the digits except for the first.

#include <iostream>
using namespace std;
int main(){
    unsigned int integer;
    unsigned char character;
    cin >> integer;
    character = integer;
    cout << character ;
}

The problem is I don't know how assigning an int value to a character object truncates the digits except for the first.

Let's for the sake of illustration assume that char is unsigned and is 8 bits wide, and int is 32 bits wide. What such an assignment would do is chop off the top 24 bits, leaving the bottom 8.

The truncation does not have anything to do with the decimal digits of the integer. For example, 9999 would become 15 (because 9999 & 0xFF == 15 ).

I am not sure what you mean by "except for the first." but let me see if I can explain what is happening.

unsigned char is, I believe, required by the standard to be 1 byte in length. int is typically much longer, 4 bytes is typical. Thus when you enter a number >255, it looses all the value above that since all it can hold is one byte and leading 3 bytes of data are lost.

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