How does bit endianness affect bit shifts and IO file in C?

Let L and B be two cars. L orders its bits from LSB (Least significant bit) to MSB (most significant bit), and B from MSB to LSB. Or, in other words, L uses Little Endian while B uses the Big Endian bit - not to be confused with byte order.

Problem 1 SOLVED :

We write the following code that we want to be portable:

#include <stdio.h>

int main()
{
    unsigned char a = 1;
    a <<= 1;

    printf("a = %d\n", (int) a);

    return 0;
}

on L , it will print 2, but what happens on B ? Will it be 1 and print 0 ?.

: C99 6.5.7 , , , , << >> 2 .

2:

, :

READ:

/* program READ */
#include <stdio.h>

int main()
{
    FILE* fp;
    unsigned char a;

    fp = fopen("data.dat", "rb");
    fread(&a, 1, 1, fp);
    fclose(fp);

    return 0;
}

WRITE:

/* program WRITE */
#include <stdio.h>

int main()
{
    FILE* fp;
    unsigned char a = 1;

    fp = fopen("data.dat", "wb");
    fwrite(&a, 1, 1, fp);
    fclose(fp);

    return 0;
}

, WRITE L, B READ ? WRITE B, READ L?

, FAQ. .

+5
5

Endianness , . Endianness .

Endianness - , , , . , SPI , , .

Wikipedia :

- endianness , , , . , . - -endian (low-bit first), , (, I²C). , OSI.

, , .

+7

, bit-endianness, , C. CHAR_BIT 8 , , , , C. , - LSB MSB - . myVar & 1 .

- , . "-" - , .

, , . 100% . , - . , CHAR_BIT . , , .

+4

number>>n number<<n . number 2^n. , , n number.

6.5.7 C99:

E1 << E2 E1 E2 ; . E1 , E1 Ɨ 2 ^ E2, , , . E1 , E1 Ɨ 2 ^ E2 , ; .

E1 >> E2 E1- E2. f E1 , E1 , E1/2 ^ E2. E1 , .

, :)

+3

- . -, , .

+2

Endianness , - , , , - , .

.

int data;
char charVal;

*data = 1;
charval = *((char *) data);  // Different result based on endianness

, , char.

0

All Articles