可移植代码 - 每个字符的位数
我知道 C/C++ 标准只保证每个字符最少 8 位,理论上 9/16/42/其他任何东西都是可能的,因此所有关于编写可移植性的网站代码警告不要假设 8bpc.我的问题是这到底有多不便携"?
I know that the C/C++ standards only guarantee a minimum of 8 bits per char, and that theoretically 9/16/42/anything else is possible, and that therefore all sites about writing portable code warn against assuming 8bpc. My question is how "non-portable" is this really?
让我解释一下.在我看来,系统分为 3 类:
Let me explain. As I see it, there a 3 categories of systems:
- 计算机 - 我是指运行 Mac/Linux/Windows/Unix/*nix/posix/whatever 的台式机、笔记本电脑、服务器等(我知道这个列表并不完全正确,但你明白了).听到
char
不是 exactly 8 位的任何此类系统,我会感到非常惊讶.(如有错误请指正) - 带有操作系统的设备 - 这包括智能手机和此类嵌入式系统.虽然我不会很惊讶发现这样一个
char
超过 8 位的系统,但迄今为止我还没有听说过(如果我不知道,请再次通知我) - 裸机 - 录像机、微波炉、旧手机等.在这个领域我没有半点经验,所以在这里什么都有可能发生.但是,我真的需要我的代码在我的 Windows 桌面和微波炉之间跨平台吗?我是否有可能拥有两者共有的代码?
- Computers - I mean desktops, laptops, servers, etc. running Mac/Linux/Windows/Unix/*nix/posix/whatever (I know that list isn't strictly correct, but you get the idea). I would be very surprised to hear of any such system where
char
is not exactly 8 bits. (please correct me if I am wrong) - Devices with operating systems - This includes smartphones and such embedded systems. While I will not be very surprised to find such a system where
char
is more tham 8 bits, I have not heard of one to date (again, please inform me if I am just unaware) - Bare metal devices - VCRs, microwave ovens, old cell phones, etc. In this field I haven't the slightest experience, so anything can happen here. However, do I really need my code to be cross platform between my Windows desktop and my microwave oven? Am I likely to ever have code common to both?
底线:是否有常见的(超过 %0.001)平台(在上面的类别 1 和 2 中)其中 char
是 not 8 位?我的上述猜测是真的吗?
Bottom line: Are there common (more than %0.001) platforms (in categories 1&2 above) where char
is not 8 bits? And is my above surmise true?
推荐答案
使用limits.h
CHAR_BIT
http://www.cplusplus.com/reference/clibrary/climits/
另外,当您想使用给定的大小时,请使用 stdint.h
also, when you want to use exactly a given size, use stdint.h
相关文章