Why does this program output 64?

I found this program during an online c programming test. I tried it at my level, but I can’t understand why the output of this program is 64.

Can anyone explain the concept of this?

#include <iostream> #include <stdio.h> using namespace std; int main() { int a = 320; char *ptr; ptr = (char *)&a; printf("%d",*ptr); return 0; } 

output:

64

Thankyou.

+5
source share
5 answers

A char * points to only one byte. Assuming the byte on your system is 8 bits, the number 320 takes 2 bytes. The lower byte of them is 64, the upper byte is 1, because 320 = 256 * 1 + 64 . That is why you get 64 on your computer (a little computer).

But note that on other platforms, the so-called big-endian platforms, the result can also be 1 (the highest byte of 16 bits / 2 bytes) or 0 (the highest byte of the value is greater than 16 bits / 2 bytes).

Note that all of this assumes that the platform has 8-bit bytes. If it were, say, 10-bit bytes, you would get a different result again. Fortunately, today most computers have 8-bit bytes.

+11
source

You cannot understand this if you do not know about:

  • hex / binary represenation and
  • CPU endianess.

Enter the decimal number 320 in hexadecimal. Separate it in bytes. Assuming int is 4 bytes, you should indicate what parts of the number that go in bytes.

After that, consider the final goal of this processor and sort the bytes in that order. (First MS byte or first LS byte.)

The code refers to the byte allocated at the lowest address of the integer. What it contains depends on the ultimate goal of the processor. You will either get hex 0x40 or hex 0x00.


Note. You should not use char for this kind of thing, because it has an application-specific signature. If the data bytes contain values ​​exceeding 0x7F, you may get some very strange errors that appear / disappear inconsistently for several compilers. Always use uint8_t* when doing any form of bit / byte manipulation.

You can detect this error by replacing 320 with 384. Your small end system can either print -128 or 128, you will get different results for different compilers.

+5
source

Int is four bytes of byte data, and char is byte of byte data, char pointer can store the address one byte at a time. The binary value of 320 is 00000000 00000000 00000001 01000000 . So, char pointer ptr only points to first byte . *ptr i.e. the contents of the first byte 01000000 , and its decimal value is 64 .

0
source

What @Lundin said is enough. By the way, perhaps some basic knowledge is useful. 320 = 0x0140. a int = 4 char. Therefore, when printing the first byte, it outputs 0x40 = 64 due to cpu endianess.

0
source

ptr - char pointer a. So * ptr will give the value char a. char takes up only 1 byte, so it repeats its values ​​after 255. That is, 256 becomes 0, 257 becomes 1 and so on. Thus, 320 becomes 64.

0
source

All Articles