C/C++ packing signed char into int

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

    You could also let the compiler do the work for you.

    union packedchars {
      struct {
        char v1,v2,v3,v4;
      }
      int data;
    };
    
    packedchars value;
    value.data = 0;
    value.v1 = 'a';
    value.v2 = 'b;
    

    Etc.

提交回复
热议问题