Portable code - bits per char

2019-01-22 19:06发布

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?

Let me explain. As I see it, there a 3 categories of systems:

  1. 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)
  2. 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)
  3. 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?

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?

标签: c++ c char bits
4条回答
劫难
2楼-- · 2019-01-22 19:13

At least, similar to the integer size in 64bit architectures, future platforms may use a wider char, with more bits. ASCII characters might become obsolete, replaced by unicode. This might be a reason so be cautious.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-22 19:17

For example, many DSP have CHAR_BIT greater than or equal to 16.

查看更多
做自己的国王
4楼-- · 2019-01-22 19:21

use limits.h

CHAR_BIT

http://www.cplusplus.com/reference/clibrary/climits/

also, when you want to use exactly a given size, use stdint.h

查看更多
Fickle 薄情
5楼-- · 2019-01-22 19:25

You can normally safely assume that files will have 8 bit bytes, or if not, that 8 bit byte files can be converted to a zero padded native format by a commonly-used tool. But it is much more dangerous to assume that CHAR_BIT == 8. Currently that is almost always the case, but it might not always be the case in future. 8 bit access to memory is increasingly a bottleneck.

查看更多
登录 后发表回答