Monday, May 21, 2007

To be (signed) or NOT To be (signed!)

A few days back, we observed an interesting behavior of signed and unsigned chars.
We had an array and were using a char variable with right shift operation as subscript in order to access a member in the array. (something like foo[foobar >> 4])

I was surprized to see that for some reason, after the shifting operation, the subscript value came out to be negative. wheras (unsigned char)fobar >> 4 was giving a positive value.

I just could not digest the behavior. My argument was that memory location allocated to hold the value of foobar will have some bit pattern. I don't care what it is. When I right shift this bit pattern, it should just shift and the resultant bit pattern should be THE SAME irrespective of whether foobar is signed or unsigned.

But then it hit me. In case of signed data, the MSB is the sign bit. It does not form part of data. So when I right shift a signed data, the MSB will not move. Whereas, in case of unsigned data, Thus, if I right shift a negative number, the resultant will also be negative. And that is indeed correct, as right shifting is equivalent to division by 2.

And the subscript on an array is always treated as signed value.

So, signed and unsigned makes difference! Recall the basics :-)

2 Comments:

Blogger Swati said...

Thanks for the 'public service' as you say :-))

On a serious note, you are right about 'recall your basics' :-)

Monday, 21 May, 2007  
Blogger Mi_Ashish_Dange_Boltoy said...

That's correct dude !! Negative number is still a negative number...

Wednesday, 23 May, 2007  

Post a Comment

<< Home