Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise shift promotes unsigned char to int

Tags:

c++

linux

gcc

The following code:

unsigned char result;
result = (result << 4 );

Compiled with gcc version 4.6.4 (Debian 4.6.4-2), with the -Wconversion flag results in the warning

warning: conversion to 'unsigned char' from 'int' may alter its value [-Wconversion]

Why is that?

like image 840
Yordan Pavlov Avatar asked Jul 05 '13 13:07

Yordan Pavlov


People also ask

What does a Bitwise Shift do?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.

What happens when you bit shift an integer?

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.

Can bit shift INT?

Basically, Bitwise operators can be applied to the integer types: long, int, short, char and byte.

How Bitwise shift operator works in Python?

Python bitwise left shift operator shifts the left operand bits towards the left side for the given number of times in the right operand. In simple terms, the binary number is appended with 0s at the end.


2 Answers

Because the standard says so. The operands to binary operators undergo integral promotion, in which anything smaller than an int is promoted to int; the results of the operation have type int as well. And if the original value were, say, 0x12, the results would be 0x120, and assigning this to an unsigned char will cause a change in value. (The assigned value will be 0x20.) Whence the warning.

EDIT:

From the standard (§5.8 Shift operators): " The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand." Unlike other binary operators, there is no effort to find a common type from the two operators: the result type is that of the left operand, period. But integral promotion does still occur: the unsigned char will be promoted to int (or to unsigned int if int has a size of 1).

like image 99
James Kanze Avatar answered Oct 08 '22 04:10

James Kanze


Because the int value can be larger than can fit in an unsigned char.

Think about what will happen when result is 255 (i.e. 0xff). Shifting it left four bits will make it 4080 (or 0xff0). How will the compiler be able to squeeze that value back into result? It can't, so it simply truncates it to 240 (0xf0). In other words, the value of the integer operation result << 4 may be be altered.

like image 37
Some programmer dude Avatar answered Oct 08 '22 04:10

Some programmer dude