Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can Some one explain why I get these output?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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

>Solution :

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%27s_complement)

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading