+ 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; }
5 Réponses
+ 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)
+ 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
+ 2
Max Charlington Can you explain the *(char*)&num==1 part step by step?
+ 1
Max Charlington plzz explain the "if" part
0
Thank you Max Charlington