Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable code - bits per char

Tags:

c++

c

char

bits

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?

like image 708
Baruch Avatar asked Jul 22 '12 12:07

Baruch


1 Answers

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

like image 181
Josh Petitt Avatar answered Sep 23 '22 06:09

Josh Petitt