C / C ++ how to convert short to char

I am using ms C ++. I use struct as

    struct header   {
        unsigned port : 16;
                unsigned destport : 16;
        unsigned not_used : 7;
        unsigned packet_length : 9;


    };
struct header HR;

this is the value of the header to be added to a separate char array.

I did memcpy(&REQUEST[0], &HR, sizeof(HR));

but the packet length value is not displayed properly.

as if I assigned HR.packet_length = 31; I get -128 (in the fifth byte) and 15 (in the sixth byte).

if you can help me with this, or if this is a more elegant way to do it.

thank

+3
source share
2 answers

, packet_length 9 . , . , -128 ( 1 char ), 15 - , 6- .

( , ):

     byte 6    |     byte 5    | ...
0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 
 packet_length   |   not_used  | ...

, , (. endianness).

: - , .. , memcopying . , , , .

+2
struct header   {
  unsigned port : 16;
  unsigned destport : 16;
  unsigned not_used : 7;
  unsigned packet_length : 9;
};

int main(){
  struct header HR = {.packet_length = 31};
  printf("%u\n", HR.packet_length);
}

$gcc new.c && &./a.out
31


Update:

i , , struct. , java.

( 16 + 16 + 7 + 9) java.
, , MTU.

+1

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


All Articles