c - Printing a number in Binary always prints in Normal form(BIG Endian) even when my computer is Little Endian? -


first of all, using user defined function called showbin() print binary of integer.as can see function checks each bit of given number right position left position(msb lsb).

am using union 2 members, have stored 512 in first member(short unsigned int a),(we know normally(in big endian) binary of 512 0000 0010 0000 0000) , in next step tried print values of array c[0] , c[1]
machine little endian it outputs: 0 2,now means under hood(in memory) binary stored as: 0000 0000 0000 0010

but when print value of a using showbin() shows 0000 0010 0000 0000 in normal(big endian) way, why not output in little endian way i,e 0000 0000 0000 0010 ???? .even if computer stores number in big endian should output 2 0 right?? ???? confused..????..can 1 please explain behavior in simple words.

void showbin(unsigned short int a); int main() {     union myun     {         short unsigned int a; //2 bytes         char c[2]; //2 bytes     };     union myun som;     som.a=512;     printf("%hu %hu \n",som.c[0],som.c[1]);     printf("512 in binary:");showbin(som.a);printf("\n");//doubt here.. return 0; }  void showbin(unsigned short int a) {      int i;      unsigned short int mask=0;      unsigned short int res=0;      for(i=15;i>=0;i--)      {         mask=0;//resetting imp..         mask=mask | (1<<i);         res=a & mask;         (res==0)?printf("0"):printf("1");      } } 

your implementation of showbin not endianess dependent.

consider unsigned integer mask, left shifting 1 same multiplying 2 on platforms. in fact, c , c++ built in such way endianess not affect standards compliant code.

if wish experience endianess, need undefined in standards c , c++, simple:

int x = 42; char* m = (char*)&x; for(size_t = 0; < sizeof(x); ++i) {     unsigned char value = (unsigned char)m[i];     // bytes - e.g. use showbin display binary representation } 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -