C/C++ packing signed char into int

前端 未结 6 1392
耶瑟儿~
耶瑟儿~ 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:28

    "Goodness"
    IMHO, this is the best solution you're going to get for this. EDIT: though I'd use static_cast instead of the C-style cast, and I'd probably not use a separate method to hide the cast....

    Portability:
    There is going to be no portable way to do this because nothing says char has to be eight bits, and nothing says unsigned int needs to be 4 bytes wide.

    Furthermore, you're relying on endianness and therefore data pack'd on one architecture will not be usable on one with the opposite endianness.

    is there a ready-made solution, perhaps boost?
    Not of which I am aware.

提交回复
热议问题