Why does endianess matter between bits inside a byte?

Below is the IP structure from the library on a Linux machine

struct ip { #if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int ip_hl:4; /* header length */ unsigned int ip_v:4; /* version */ #endif #if __BYTE_ORDER == __BIG_ENDIAN unsigned int ip_v:4; /* version */ unsigned int ip_hl:4; /* header length */ #endif u_int8_t ip_tos; /* type of service */ u_short ip_len; /* total length */ u_short ip_id; /* identification */ u_short ip_off; /* fragment offset field */ #define IP_RF 0x8000 /* reserved fragment flag */ #define IP_DF 0x4000 /* dont fragment flag */ #define IP_MF 0x2000 /* more fragments flag */ #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ u_int8_t ip_ttl; /* time to live */ u_int8_t ip_p; /* protocol */ u_short ip_sum; /* checksum */ struct in_addr ip_src, ip_dst; /* source and dest address */ }; 

for these lines:

  #if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int ip_hl:4; /* header length */ unsigned int ip_v:4; /* version */ #endif #if __BYTE_ORDER == __BIG_ENDIAN unsigned int ip_v:4; /* version */ unsigned int ip_hl:4; /* header length */ #endif 

Why is enterian important in bytes? I think endianess only affects multibyte integers, but here it seems to me that endianess also affects the location of bits inside a byte?

furthermore, it is only a byte, why is it unsigned int which is 4 bytes.

I see in wirehark, ip_v and ip_hl is displayed as 0x45 if I grab the IP packet. The first byte consists of ip_v and ip_hl. I put it in the character variable x

, what is the result of x & 0b11110000 ? Is there always 4 no purpose, or can it be 5?

+4
source share
2 answers

Endianess determines the location of the most significant bit (MSB); it is related to how the number inside the variable is interpreted in memory. Considering unsigned integers:

 00000001 (Binary) = 1 (2 to the power of 0) -> If the most significant bit is to the left 00000001 (Binary) = 128 (2 to the power of 7) -> If the most significant bit is to the right 

As you can see, the position of the most significant bit is very important when it comes to representing a number in memory, even in 8-bit numbers.

For your last question you are right, it does not matter if it is 1 byte or 4, because it takes only 4 bits. But remember that unsigned int is not always a 4 byte number.

Hope this helps!

+1
source

There is a byte order that matters in the case of multiple byte data. But in your case, bit field ordering matters, which deals with the order of bits in the case of a single byte data. There are no rules proposed by the C standard regarding bit field ordering. It is implementation dependent and is determined by the compiler.

The size of the variable is not 4 bytes. This is just 4 bits. They are not independent variables. These are bit fields within the structure.

+3
source

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


All Articles