"unsigned char" portability issues

Erik Trulsson ertr1013 at student.uu.se
Wed Apr 9 09:33:54 PDT 2003


On Wed, Apr 09, 2003 at 03:50:32PM +0100, Robin Carey wrote:
> 
> Dear FreeBSD-questions,
> 
> I am writing some free software which uses the "unsigned char" C type.
> 
> Some people have been raising the issue that the "unsigned char" type
> might be bigger than 8-bits and that there is therefore portability
> issues with it.
> 
> Yet this C type is used in OpenSSL and in the SHA and MD5 routines
> shipped with FreeBSD, and the way in which it is used in these
> programs implicitly assumes it is exactly one byte in size.
> 
> Can someone please give me some good advice on this issue ?
> 
> Does the "unsigned char" type vary in size for different FreeBSD architectures ?
> 
> Any help would be appreciated,

In the C standard 'char' (as well as 'unsigned char') and 'byte' are
defined to be equivalent. This is not necessarily true for other
definitions of 'byte'.

The C standard says that a 'char' must be at least 8 bits wide, but it
is allowed to be wider.

Contrary to popular perception a byte is not necessarily 8 bits wide.
On just about all architectures in common use today (and certainly on
all architectures FreeBSD runs on) a byte is exactly 8 bits wide but on
some older systems (e.g. PDP-10) a byte can have another width.

There are C compilers out there where a 'char' is not exactly 8 bits
wide.  (I think one Cray compiler had all the integer types
(char,short,int and long) being 64 bits wide.)

Any C code that assumes that 'char' (or 'unsigned char') is exactly 8
bits wide is strictly speaking not portable.  (Nor is code that cannot
handle that 'int' might be 19 bits wide and 'long' be 37 bits wide.)

On the other hand code that is part of an OS can make many unportable
assumptions since one has control over the environment in which the
code will be run.

All architectures that FreeBSD currently runs on, as well as any it is
likely to be ported to in the forseeable future, has 8-bit bytes, so
any code which is FreeBSD specific can assume such.
Code which is intended to be portable to a wide variety of systems on
the other hand cannot make such assumptions.


-- 
<Insert your favourite quote here.>
Erik Trulsson
ertr1013 at student.uu.se


More information about the freebsd-questions mailing list