cpointersendiannessbit

how is data stored at bit level according to "Endianness"?


I read about Endianness and understood squat...

so I wrote this

main()
{
    int k = 0xA5B9BF9F;

    BYTE *b = (BYTE*)&k;    //value at *b is 9f
    b++;    //value at *b is BF
    b++;    //value at *b is B9
    b++;    //value at *b is A5
}

k was equal to A5 B9 BF 9F

and (byte)pointer "walk" o/p was 9F BF b9 A5

so I get it bytes are stored backwards...ok.

~

so now I thought how is it stored at BIT level...

I means is "9f"(1001 1111) stored as "f9"(1111 1001)?

so I wrote this

int _tmain(int argc, _TCHAR* argv[])
{
    int k = 0xA5B9BF9F;
    void *ptr = &k;
    bool temp= TRUE;
    cout<<"ready or not here I come \n"<<endl;

    for(int i=0;i<32;i++)
    {   
        temp = *( (bool*)ptr + i );
        if( temp )
            cout<<"1 ";
        if( !temp)
            cout<<"0 ";
        if(i==7||i==15||i==23)
            cout<<" - ";
   }
}

I get some random output

even for nos. like "32" I dont get anything sensible.

why ?


Solution

  • Endianness, as you discovered by your experiment refers to the order that bytes are stored in an object.

    Bits do not get stored differently, they're always 8 bits, and always "human readable" (high->low).

    Now that we've discussed that you don't need your code... About your code:

    for(int i=0;i<32;i++)
    {   
      temp = *( (bool*)ptr + i );
      ...
    }
    

    This isn't doing what you think it's doing. You're iterating over 0-32, the number of bits in a word - good. But your temp assignment is all wrong :)

    It's important to note that a bool* is the same size as an int* is the same size as a BigStruct*. All pointers on the same machine are the same size - 32bits on a 32bit machine, 64bits on a 64bit machine.

    ptr + i is adding i bytes to the ptr address. When i>3, you're reading a whole new word... this could possibly cause a segfault.

    What you want to use is bit-masks. Something like this should work:

    for (int i = 0; i < 32; i++) {
      unsigned int mask = 1 << i;
      bool bit_is_one = static_cast<unsigned int>(ptr) & mask;
      ...
    }