C / C ++将signed char转换为int [英] C/C++ packing signed char into int
问题描述
我需要将四个有符号字节打包成32位整数类型。
这是我想到的:
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(char c0, char c1, ...) {
return byte(c0) | byte(c1) << 8 | ...;
}
这是一个很好的解决方案吗?它是便携式的(不是在通信意义上)?
is this a good solution? Is it portable (not in communication sense)? is there a ready-made solution, perhaps boost?
问题我最关心的是将位从char转换为int时的位顺序。
issue I am mostly concerned about is bit order when converting of negative bits from char to int. I do not know what the correct behavior should be.
感谢
推荐答案
p>我喜欢Joey Adam的答案,除了它是用宏编写的(这在许多情况下导致真正的痛苦),如果'char'不是1字节宽,编译器不会给你警告。这是我的解决方案(基于Joey的)。
I liked Joey Adam's answer except for the fact that it is written with macros (which cause a real pain in many situations) and the compiler will not give you a warning if 'char' isn't 1 byte wide. This is my solution (based off Joey's).
inline uint32_t PACK(uint8_t c0, uint8_t c1, uint8_t c2, uint8_t c3) {
return (c0 << 24) | (c1 << 16) | (c2 << 8) | c3;
}
inline uint32_t PACK(sint8_t c0, sint8_t c1, sint8_t c2, sint8_t c3) {
return PACK((uint8_t)c0, (uint8_t)c1, (uint8_t)c2, (uint8_t)c3);
}
我省略了转换c0-> c3到uint32_t作为编译器应该处理这个为你移动时,我使用c风格的casts,因为他们将工作为c或c ++(OP标记为两者)。
I've omitted casting c0->c3 to a uint32_t as the compiler should handle this for you when shifting and I used c-style casts as they will work for either c or c++ (the OP tagged as both).
这篇关于C / C ++将signed char转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!