Converting byte order on a network using char

I have always been taught that if an integer is greater than char, you should solve the byte order problem. Usually I just port it to hton [l | s] and transform it back with ntoh [l | s]. But I am confused why this does not apply to single byte characters.

I'm sick of wondering why this is, and I would like an experienced network programmer to help me shed some light on why byte orders apply only to multi-byte integers.

Link: https://beej.us/guide/bgnet/html/multi/htonsman.html

+5
source share
7 answers

What you are looking for is endianness .

, :

big endian

little-endian :

little-endian

, , .

, .

+19

, , .

+4

char?

+4

, . , . :

#include <stdio.h>
#include <netinet/in.h>

int main () {
    uint16_t i = 42;
    uint8_t c = 42; // a char
    printf ("(uint16_t ) %08X (%d)\n", i, i);
    printf ("(   htons ) %08X (%d)\n", htons(i), htons(i));
    printf ("( uint8_t ) %08X (%c)\n", c, c);
    printf ("(   htons ) %08X (%c)\n", htons(c), htons(c));
    return 0;
}

(uint16_t ) 0000002A (42)
(   htons ) 00002A00 (10752)
( uint8_t ) 0000002A (*)
(   htons ) 00002A00 ()
+3

, . , , "I" .

+2

, : Endianness - , . , . - , ( "--" ). , char , , , .

0

ezpz .

uint16_t i = 65534;
printf ("(uint16_t ) %08X (%d)\n", i, i);

Returns...
(uint16_t ) 0000FFFE (-2)

Instead, you should use unsigned int so that it is not interpreted as a signed int

uint16_t i = 65534;
printf ("(uint16_t ) %08X (%u)\n", i, i);

Returns...
(uint16_t ) 0000FFFE (65534)
0
source

All Articles