Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing negative numbers

Tags:

c

In this code below

int main()
{
int  a = -1;
printf("%d",a>>1);
return 0;
}

Why it is giving output -1.

like image 563
algo-geeks Avatar asked Mar 29 '11 18:03

algo-geeks


People also ask

Which datatype is used to store negative numbers?

Floating-Point Data Example On all machines, variables of the float, double, and long double data types can store positive or negative numbers.

Can negative numbers be stored in registers?

Login [Register]Storing negative numbers, however, is legal, but the number will get "wrapped" to fit. For example, if you assign -1 to A, it will really hold 255. If you assign -2330 to BC, it will really hold 63206. Adding one plus the maximum value the register will hold gives you the value that will be stored.

Can we store negative value in long?

Does long long not support negative values ? Yes it does support negative values as long as it is not appended after unsigned .

How are negative numbers stored in a processor?

The leftmost or the most significant bit is the sign bit. It tells the processor about the sign of the number – that is, whether the number is positive or negative. 0 in the sign bit represents a positive value and 1 represents a negative value.


2 Answers

bit-shifting is defined only on unsigned types, for signed types it is implementation-defined. And this is a useful refinement by R..

Strictly speaking, it is defined for signed types whenever the value is positive and the result does not overflow, and right shift is implementation-defined for negative values. Left shift, on the other hand, is undefined for negative values

┌───┬──────────────┬──────────────────────────────────┬────────────────────────┐
│   │ Unsigned     │ Signed, positive                 │ Signed, negative       │
├───┼──────────────┼──────────────────────────────────┼────────────────────────┤
│<< │ well-defined │ well-defined, except on overflow │ undefined behaviour    │
│>> │ well-defined │ well-defined                     │ implementation-defined │
└───┴──────────────┴──────────────────────────────────┴────────────────────────┘
like image 143
Armen Tsirunyan Avatar answered Oct 06 '22 22:10

Armen Tsirunyan


Because -1 is 1111111...111 in binary. a>>1 operation will "sign extend" the sign bit, so you get 1111111...111 again.

like image 35
Joel Lee Avatar answered Oct 07 '22 00:10

Joel Lee