Angus
Angus

Reputation: 12631

unsigned integer in c

Given a program like below how to identify that whether the signed integer will go to a -ve or +value.

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

This outputs in -ve.But is there any easy way to identify it quickly without executing in visual studio.

Upvotes: 2

Views: 246

Answers (5)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215597

0xDEADBEEF is larger than INT_MAX on your system (0x7FFFFFFF), so the conversion to int is implementation-defined. Common twos complement implementations define it as reduction modulo 2*INT_MAX+2 into the range [INT_MIN,INT_MAX].

Upvotes: 0

Femaref
Femaref

Reputation: 61497

With some bitwise magic:

int negative = (input >> ((sizeof(int) * 8) - 1)) & 0x01;

To explain it:

In C, negative numbers are two's-complement, where the highest bit denotes the sign. We first determine how many bits an int has on the current platform using sizeof(int) * 8. To get the highest bit via right shift, we need to shift by size - 1. As the right shift is arithmetical in C (meaning if the highest bit is 1, we fill the int with 1s from the left on), we need to kill all extra bits using logical and with 0x01 (or simply 1, whatever you prefer).

The result is an int with value 1 if the input is negative, or 0 if it is positive.

If you want to do it on paper, take the highbyte (in your case, DE), write out the upper half (D) and check wether the highbit of that is a zero or one.

Upvotes: 6

eugene_che
eugene_che

Reputation: 1997

If the first bit (sign bit) is 1, then the value is negative. Otherwise it is positive.

BTW, there is one more negative number compared with amount of the positive numbers.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799450

See if the value is less than 0x80, 0x8000, 0x80000000, or 0x8000000000000000, depending on the bit depth of the type. If it is less than then it's positive, otherwise it's negative.

Upvotes: 3

Jens Gustedt
Jens Gustedt

Reputation: 78983

You'd have to know the width (number of value bits) in int to decide on that.

You'd also have to give a \n at the end of your format string to be sure to have an output.

Upvotes: 0

Related Questions