Home > Software engineering >  Can Some one explain why I get these output?
Can Some one explain why I get these output?

Time:05-25

I am new to c.

My Question.

Why do some numbers end up negative when the value was positive? Why do some small numbers end up with a huge magnitude when typecast to unsigned?

#include <stdio.h>
#include <stdbool.h>
#include <limits.h>


void typecast(int a)
{
    unsigned b = (unsigned) a;
    unsigned char c = (unsigned char) a;
    char d = (char) a;
    unsigned long e = (unsigned long) a;
    long f = (long) a;
    
    printf(" %d : \n",a);
    printf(" ->unsigned int: %u\n",b);
    printf(" ->unsigned char (as decimal) %u\n",c);
    printf(" ->char (as decimal) %d\n",d);
    printf(" ->unsigned long: %lu\n",e);
    printf(" ->long: %ld\n",f);
}


int main()
{
    int num=0;
    printf("Enter an integer: ");
    scanf("%d", &num);
    typecast(num);
    
  return 0;
}

OUTPUT:

Enter an integer: 1000
1000 :
->unsigned int: 1000
->unsigned char (as decimal) 232
->char (as decimal) -24
->unsigned long: 1000
->long: 1000

CodePudding user response:

Here is an explanation for the output you are seeing. 1000 in binary is 1111101000 (10 bits) and is stored in an int (signed 32 bits)

When you cast that to an unsigned char (that has 8 bits), the top bits get "cut off".

So you get: 11101000 which is 232 in decimal.

As a (signed) char, the bits get interpreted as a negative number because the first (sign) bit is set, which in this case is -24.

When you remove the sign bit, 1101000 = 104

The "value" of the MSB is 128, so your computer does 104 - 128 = -24.

(See https://en.wikipedia.org/wiki/Two's_complement)

A long has the same or more bits as an int so the value does not change.

  • Related