Enter int char in printf () in C

int *int_pointer = malloc(10);

*int_pointer = 53200;

printf("The integer at byte #0 is set to: %d \n", (char) *int_pointer);

RESULT: -48

So, I was just trying to figure out what was going to happen, and I got this unexpected result.

Why is -48? How did this turn into a negative?

+2
source share
4 answers

Legal entity prospect:

I believe the correct reference in the C99 / C11 standard §6.3.1.3(with emphasis on mine):

  • When a value with an integer type is converted to another integer type other than _Bool, if the value can be represented by a new type, it has not changed.
  • , , , , , , .
  • , ; , , .

, char , , unsigned. , , unsigned char.

:

, sizeof(int) == 4 , 53200 :

0000 0000 0000 0000 1100 1111 1101 0000

, CPU (, ), , , , , .. :

0000 1101 1111 1100 0000 0000 0000 0000

, (unsigned char) 53200 , ( ) (, , sizeof(unsigned char) == 1):

53200 - 256 - 256 - ... - 256 = 53200 % 256 = 208

1101 0000

, "", , .

printf():

@pmg printf() , - unsigned char ( signed char char) int, " ".

:

biwise & , :

*int_number & 0xff   /* mask is 0000 0000 0000 0000 1111 1111 */
+8

, , - undefined. undefined , , , , , , .

: " ?" - , 52301, 42, "! !" .

+5

: 53200 = 0xCFD0 0xCF= 207, a signed char= -48...

+2

I think @fritzone is correct.
Since the range of integers in C is equal -32768 to 32767and therefore after 32767 it will go for -32768, not 32768, and therefore it prints -48 instead of 53200.
Try the value 53201 and it will output the value -47, etc.

+1
source

Source: https://habr.com/ru/post/1661558/


All Articles