Plzz someone explain this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Plzz someone explain this

#include <iostream> using namespace std; int main() { int num = 1; if(*(char*)&num==1) cout<<"Little-endian"<<endl; else cout<<"Big-endian"<<endl; return 0; }

19th May 2020, 10:59 AM
Sayed Ayaan
Sayed Ayaan - avatar
5 Answers
+ 3
The code takes first byte of integer value of 1. If it is also 1 this means that left bytes are lower ones and it is little endian. If first byte of an int with value 1 is 0, this would mean left bytes are higher value (big endian)
19th May 2020, 11:12 AM
Max Charlington
Max Charlington - avatar
+ 3
&num - address of num (char*) - cast type of to char pointer (char*)&num - takes num address and interprets it as a char pointer(all pointers inside are 32bit values on x86) *(char*)&num - returns the actual char value at address of num For instance: 1 as int in memory looks like 1 bit and another 31 0 bits. If u take first byte of integer(which is 4 bytes BTW) u get 1 bit and 7 0bits, which is 1 char value on little endian. On big endian 1 value integer is 31 0bits and 1 1bit. So if u take first byte of this int, u will get 8 0bits (0 value char) Hope this clears everything
19th May 2020, 11:39 AM
Max Charlington
Max Charlington - avatar
+ 2
Max Charlington Can you explain the *(char*)&num==1 part step by step?
19th May 2020, 11:18 AM
Infinity
Infinity - avatar
+ 1
Max Charlington plzz explain the "if" part
19th May 2020, 11:19 AM
Sayed Ayaan
Sayed Ayaan - avatar
0
Thank you Max Charlington
19th May 2020, 12:21 PM
Sayed Ayaan
Sayed Ayaan - avatar