How is bit level data stored according to "Endianness"?

I read about Endianness and understood squats ...

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 A5 B9 BF 9F

and (byte) the o / p " walk " pointer was9F BF b9 A5

so I get that the bytes are stored in reverse order ... ok.

~

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

Does I mean "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 do not get anything reasonable.

why?

+3
source share
5 answers

Endianness, , , .

-, 8 "" ( → ).

, , ... :

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

, , . 0-32, - . temp :)

, a bool* , int* , BigStruct*. - 32 32- , 64 64- .

ptr + i i ptr. i>3, ... segfault.

, , - -. - :

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

, .

Intel x86 Consistent Little Endian, LSB MSB . b0 = 2 ^ 0 b31 = 2 ^ 31.

Motorola 68000 Big Endian, MSB LSB . b0 = 2 ^ 0 b31 = 2 ^ 31 ( , intel, "" Big Endian).

32- IBM/Motorola PowerPC Consistent Big Endian, MSB LSB . b0 = 2 ^ 31 b31 = 2 ^ 0.

. .

+6

, . Endianness .

( , - ), , & .

+3

Endianness

:

union endian_example {
   unsigned long u;
   unsigned char a[sizeof(unsigned long)];
} x;

x.u = 0x0a0b0c0d;

int i;
for (i = 0; i< sizeof(unsigned long); i++) {
    printf("%u\n", (unsigned)x.a[i]);
}

, . . .

-. - (>>, <<), , . . ( ).

C , - . ( ) "" C, , struct.

struct thing {
     unsigned y:1; // y will be one bit and can have the values 0 and 1
     signed z:1; // z can only have the values 0 and -1
     unsigned a:2; // a can be 0, 1, 2, or 3
     unsigned b:4; // b is just here to take up the rest of the a byte
};

endianness . y thing? ? ( , IPv4, ), , , , - . , , , .

+3

:

temp = *( (bool*)ptr + i );

... , , , , , . void * bool *, "bool", , , int , .

, , . ( , , ). , , - , , I2C RS232 , . , , , "int 0xAABBCCDD" "- 11100011... [] ".

+2

Source: https://habr.com/ru/post/1747616/


All Articles