-4

How will this program get executed?

#include <stdio.h>

void main() { 
    char a = 0xAA;
    int b;
    b = (int) a;
    printf("%d\n", a); 
    b = b >> 4;
    printf("%x", b); 
}

[Question]

I have problem in statement b = (int)a. Can you give the binary representation of b when a is stored in it?

Grijesh Chauhan
  • 55,177
  • 19
  • 133
  • 197

3 Answers3

1

For the statement b = (int)a;, we are typecasting a char to an int. Assuming that char is implicitly signed (NB: not always true!) and that int is 32 bits, then the char value 0xAA gets widened with sign extension, so 0xAA becomes 0xFFFFFFAA which is equivalent to -86 in decimal.

Paul R
  • 202,568
  • 34
  • 375
  • 539
1
char a = 0xAA; // line 1
int b; // line 2
b = (int) a; // line 3
printf("%d\n", a); // line 4
b = b >> 4; // line 5
printf("%x", b); // line 6

Line 1: assigned a character to variable a of char type from hexadecimal

Line 2: declaring a variable b of int type

Line 3: Assign value of char a by typecasting to from char to int. It will output a int value.

Line 4: outputs the value of char a in int format

Line 5: reassign value of b by right shifting it to 4.

Line 6: Output value of b in hexadecimal format. So output should be in something e.g.; FFAA454 like.

This is how your code is working.

Ashwani
  • 3,387
  • 1
  • 23
  • 30
0

If you want to know what the console will output, here is what I get:

-86
fffffffa

In the future if you want to see how a test case is executed try using something like this.

Christian Wilkie
  • 3,491
  • 5
  • 30
  • 47