Basic doubt in datatypes of signed and unsigned

H

hari

Hi,

#include <stdio.h>
#include<conio.h>
int main()
{
int x= -1;
unsigned int y = x ;
unsigned int j = y;

printf("%x %x",x,y)
return 0;
}

When I execute this,I' m getting the output as 0xfffffff
0xfffffff.My expectation is , y is unsigned int,so on assigning a
signed variable with value -1.It should go to 0.

Please correct me if I' m wrong .

Regards
Hari
 
T

Tomás Ó hÉilidhe

#include<conio.h>


Just so you know, conio.h is not a part of the C Standard. For this
particular program, you don't even need conio.h.

int main()
{
                int x= -1;
                unsigned int y = x ;


When you convert a signed integer to an unsigned integer, the value
you're left with is as follows:

(WHATEVER_UNSIGNED_INT_TYPE_MAX + 1) + (-the_negative_value)

So in your case, it's:

(UINT_MAX + 1) - (1)

And so that becomes:

UINT_MAX
 
J

James Kuyper

hari said:
Hi,

#include <stdio.h>
#include<conio.h>
int main()
{
int x= -1;
unsigned int y = x ;
unsigned int j = y;

printf("%x %x",x,y)
return 0;
}

When I execute this,I' m getting the output as 0xfffffff

Are you sure that wasn't 0xffffffff? A value of 0xfffffff is technically
possible, but extremely unlikely unless you're using a very unusual machine.
0xfffffff.My expectation is , y is unsigned int,so on assigning a
signed variable with value -1.It should go to 0.

Please correct me if I' m wrong .

If an integer value is outside the valid range for an unsigned integer
type, when you convert that value to that type, the result is determined
using modulus arithmetic. This means that you first determine the number
that is 1 larger than the largest value that can be stored in in the
unsigned type; in your case, that would be UINT_MAX+1, which is probably
0x100000000 (assuming that I was right about you mis-counting the number
of 'f's). Then you repeatedly either add or subtract this number from
the value, until you get a result that is in range for the unsigned
type. In this case, a single addition of UINT_MAX+1 to -1 gives you a
value of UINT_MAX, which is within range, so that's the result you
should be getting.
 
P

Phil Carmody

James Kuyper said:
*ahem*


Are you sure that wasn't 0xffffffff?

Odd that you should expect one character more, I would have expected
one character fewer.

Phil
 
J

James Kuyper

Phil said:
Odd that you should expect one character more, I would have expected
one character fewer.

Yes, that leading 0 shouldn't appear in his output, and I shouldn't have
included it in my proposed alternative.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top