Here is a program
#include <stdio.h>
main()
{ unsigned char i=0x80;
printf("i=%d",i<<1);
}
The output it is giving is 256. I am not clear with what does
unsigned char i=0x80; <-- i is not int it is char so what will it store?
I know bitshift and hexadecimal things. How is the value of i being stored and how does it gets changed to 256?
UPDATE
Why did overflow not occurred when the bit shift operation happened?
0x80 is the most significant bit of an 8-bit byte set. If it is stored in a signed char (on a machine that uses 2's-complement notation - as most machines you are likely to come across will), it is the most negative value (decimal -128); in an unsigned char, it is decimal +128.
Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.
0X80 is a hexadecimal (hex) number. We can tell it is a hex number because it starts with 0X. Hexadecimal numbers like 0X80 are not often used in daily life, but we see them used for certain things such as html colors, shortening binary numbers, computer error codes, and math exercises.
Overview. 0xff is a number represented in the hexadecimal numeral system (base 16). It's composed of two F numbers in hex. As we know, F in hex is equivalent to 1111 in the binary numeral system. So, 0xff in binary is 11111111.
In C, a char
is an integer type used to store character data, typically 1 byte.
The value stored in i
is 0x80
a hexidecimal constant that is equal to 128
.
An arithmetic operation on two integer types (such as i << 1
) will promote to the wider type, in this case to int
, since 1
is an int constant. In any case, integer function arguments are promoted to int.
Then you send the result to printf
, with a %d
format specifier, which mean "print an integer".
I think that K&R have the best answer to this question:
2.7 Type Conversions When an operator has operands of different types, they are converted to a common type according to a small number of rules. In general, the only automatic conversions are those that convert a
narrower'' operand into a
wider'' one without losing information, such as converting an integer into floating point in an expression like f + i. Expressions that don't make sense, like using a float as a subscript, are disallowed. Expressions that might lose information, like assigning a longer integer type to a shorter, or a floating-point type to an integer, may draw a warning, but they are not illegal. A char is just a small integer, so chars may be freely used in arithmetic expressions.
So i<<1 converts i to int before it is shifted. Ken Vanerlinde has it right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With