0

int a = 320; char *ptr; ptr = (char*)&a; printf("%d", *ptr); // how the output is 64? Please explain.

8th Aug 2021, 8:38 AM
NIKHIL JOSHI
NIKHIL JOSHI - avatar
2 odpowiedzi
+ 7
Short: 320-256=64 Long: a char is ranged from -128 to 127. When it goes beyond 127 it goes back to -128 and count to -127, -126 and so on. Adding the number of negative, zero and positive numbers, we can get 256, meaning by adding or subtracting 256, the char value remained the same. It's kind of like a circle where 361 degree is as same as 1 degree.
8th Aug 2021, 8:48 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
On a little-endian machine (supposing int is 4bytes, byte is 8bits) 320 shell be stored as: 01000000 00000001 00000000 00000000 (2^6+2^8) You then ask the program to read just the first char (=1byte), which is: 0100000 = 2^6 = 64 If on the other hand yours was a big-endian machine, then the result would be 0
8th Aug 2021, 3:08 PM
Angelo
Angelo - avatar