C/C++ packing signed char into int

前端 未结 6 1403
耶瑟儿~
耶瑟儿~ 2021-01-19 15:47

I have need to pack four signed bytes into 32-bit integral type. this is what I came up to:

int32_t byte(int8_t c) { return (unsigned char)c; }

int pack(cha         


        
6条回答
  •  余生分开走
    2021-01-19 16:46

    char isn't guaranteed to be signed or unsigned (on PowerPC Linux, char defaults to unsigned). Spread the word!

    What you want is something like this macro:

    #include  /* Needed for uint32_t and uint8_t */
    
    #define PACK(c0, c1, c2, c3) \
        (((uint32_t)(uint8_t)(c0) << 24) | \
        ((uint32_t)(uint8_t)(c1) << 16) | \
        ((uint32_t)(uint8_t)(c2) << 8) | \
        ((uint32_t)(uint8_t)(c3)))
    

    It's ugly mainly because it doesn't play well with C's order of operations. Also, the backslash-returns are there so this macro doesn't have to be one big long line.

    Also, the reason we cast to uint8_t before casting to uint32_t is to prevent unwanted sign extension.

提交回复
热议问题