"unsigned char" portability issues

Joel Rees joel at alpsgiken.gr.jp
Wed Apr 9 19:21:55 PDT 2003


(Line hard-wrapping by me.)

> 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.

I think <limits.h> is still a standard header. It has constants that
will help with portability issues. For instance, somewhere around the
parts of your code that will fail if an unsigned char is not 8 bits, you
can say 

    #if CHAR_BIT != 8 || UCHAR_MAX != 255
    #   error "Can't compile on this architecture!"
    #endif

and at least you can help people trying to move your code to a Cray or a
Univac 1100 to spot what they will have to tweak.

Using both of those tests might be overkill. (Now, I wonder why there
isn't a UCHAR_MIN? ;) 

You might also be interested in doing something like

    #if CHAR_BIT == 8 && UCHAR_MAX == 255
        #if CHAR_MAX == UCHAR_MAX
            typedef char my_char_t;
        #else
            typedef unsigned char my_char_t;
        #endif
    #else
    #   error "Can't compile on this architecture!"
    #endif

And, of course, that might also be overkill.

> 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 ?

See Erik's comments, if you haven't already. 

If porting to Linux or the other BSDs is expected, you probably will
want to use something like the above. If the  sort of warning given
above is insufficient, you might actually need to encapsulate more than
just a typedef in these kinds of pre-processor tests.

If you need further help on C, there are some newgroups out there, for
instance,

    http://groups.google.com/groups?group=comp.lang.c

HTH

-- 
Joel Rees <joel at alpsgiken.gr.jp>



More information about the freebsd-questions mailing list