Kurs programowania w C cz. 154

Nasza ocena:

3
Wyświetleń: 560
Komentarze: 0
Notatek.pl

Pobierz ten dokument za darmo

Podgląd dokumentu
Kurs programowania w C cz. 154 - strona 1

Fragment notatki:

174 ROZDZIAŁ 24. PRZENOŚNOŚĆ PROGRAMÓW int main() { #if __BYTE_ORDER == __BIG_ENDIAN printf("Porządek big-endian (4321)\n"); #elif __BYTE_ORDER == __LITTLE_ENDIAN printf("Porządek little-endian (1234)\n"); #elif defined __PDP_ENDIAN && __BYTE_ORDER == __PDP_ENDIAN printf("Porządek PDP (3412)\n"); #else printf("Inny porządek (%d)\n", __BYTE_ORDER); #endif return 0; } Na podstawie makra BYTE ORDER można skonstruować funkcję, która będzie kon- wertować liczby pomiędzy porządkiem różnymi porządkami: #include  #include  #include  uint32_t convert_order32(uint32_t val, unsigned from, unsigned to) { if (from==to) { return val; } else { uint32_t ret = 0; unsigned char tmp[5] = { 0, 0, 0, 0, 0 }; unsigned char *ptr = (unsigned char*)&val; unsigned div = 1000; do tmp[from / div % 10] = *ptr++; while ((div /= 10)); ptr = (unsigned char*)&ret; div = 1000; do *ptr++ = tmp[to / div % 10]; while ((div /= 10)); return ret; } } #define LE_TO_H(val) convert_order32((val), 1234, __BYTE_ORDER) #define H_TO_LE(val) convert_order32((val), __BYTE_ORDER, 1234) #define BE_TO_H(val) convert_order32((val), 4321, __BYTE_ORDER) #define H_TO_BE(val) convert_order32((val), __BYTE_ORDER, 4321) #define PDP_TO_H(val) convert_order32((val), 3412, __BYTE_ORDER) #define H_TO_PDP(val) convert_order32((val), __BYTE_ORDER, 3412) int main () { printf("%08x\n", LE_TO_H(0x01020304)); printf("%08x\n", H_TO_LE(0x01020304)); printf("%08x\n", BE_TO_H(0x01020304)); printf("%08x\n", H_TO_BE(0x01020304)); printf("%08x\n", PDP_TO_H(0x01020304)); printf("%08x\n", H_TO_PDP(0x01020304)); return 0; } Ciągle jednak polegamy na niestandardowym pliku nagłówkowym endian.h. Można go wyeliminować sprawdzając porządek bajtów w czasie wykonywania programu: ... zobacz całą notatkę



Komentarze użytkowników (0)

Zaloguj się, aby dodać komentarz