Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this program output 64?

Tags:

c

I found this program during an online test on c programming I tried it on my level but I cannot figure it out that why the output of this program comes out to be 64.

Can anyone explain the concept behind 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.

like image 805
Mayur Kharche Avatar asked Jul 01 '16 08:07

Mayur Kharche


2 Answers

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

But note that on other platforms, so called big-endian platforms, the result could just as well be 1 (the most significant byte of a 16 bit/2 byte value) or 0 (the most significant byte of a value larger than 16 bit/2 bytes).

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

like image 89
Rudy Velthuis Avatar answered Oct 28 '22 19:10

Rudy Velthuis


You won't be able to understand this unless you know about:

  1. hex/binary represenation, and
  2. CPU endianess.

Type out the decimal number 320 in hex. Split it up in bytes. Assuming int is 4 bytes, you should be able to tell which parts of the number that goes in which bytes.

After that, consider the endianess of the given CPU and sort the bytes in that order. (MS byte first or LS byte first.)

The code accesses the byte allocated at the lowest address of the integer. What it contains depends on the CPU endianess. You'll either get hex 0x40 or hex 0x00.


Note: You shouldn't use char for these kind of things, because it has implementation-defined signedness. In case the data bytes contains values larger than 0x7F, you might get some very weird bugs, that inconsistently appear/disappear across multiple compilers. Always use uint8_t* when doing any form of bit/byte manipulation.

You can expose this bug by replacing 320 with 384. Your little endian system may then either print -128 or 128, you'll get different results on different compilers.

like image 24
Lundin Avatar answered Oct 28 '22 19:10

Lundin