Click here to Skip to main content
15,902,189 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Question :

C++
#include <stdio.h>
int main( ) {
       signed int num = 0xDEADBEE;
}
What is the sign of the variable num ?
Posted
Updated 15-Jan-13 21:11pm
v2

1 solution

Depends.

If you are running in a system where int is a 16 bit value, then you will either get an overflow compilation error, or a negative value.
In a 32 bit integer system (or higher) the value would be positive.

It's all about the most significant bit of signed integers - if it is zero, it's positive, if one it's negative. Since your value has only 28 bit positions defined out if a possible 32, the remaining 4 bits will be zero, and the result is a positive number.

Most modern compilers (except for embedded work) are 32 bit, with occasional 64 or higher for specialist applications. Embedded compilers (or cross compilers) may well be 16 bit.

"Dear sir, If the signed num is 0x16 then its binary form is 0001 0110 the msb is 0 --> positive.
for the negative signed num,how to find and locate that msb? eg : 0xA and 0xABDE for both scenarios is same or not?"


Not quite!
If the value is 0x16 then it's binary form is not
0001 0110
it is
0000 0000 0001 0110
for a sixteen bit system, and
0000 0000 0000 0000 0000 0000 0001 0110
for a thirty-two bit system.
The position of the MSB changes according to the size of the variable it is going into. So you need to know what size data you are working with in order to decide if a given value is positive or negative.
(This is one advantage of working with C# and similar .NET langauges: int is defined by the language specification as a synonym for int32 - a thirty-two bit signed integer.)

For a sixteen bit system, "just the MSB" is 0x8000, for a thirty-two bit system it is 0x80000000
Binary ANDing with this value will tell you if it is positive or negative.
 
Share this answer
 
v2
Comments
mvigsnhwar 16-Jan-13 4:25am    
Dear sir, If the signed num is 0x16 then its binary form is 0001 0110 the msb is 0 --> positive.
for the negative signed num,how to find and locate that msb? eg : 0xA and 0xABDE for both scenarios is same or not?
OriginalGriff 16-Jan-13 4:47am    
Answer updated
SajeeshCheviry 16-Jan-13 5:03am    
good answer :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900