Bitfields and printf()

Darrin A. Hyrup magik at sorinc.UUCP
Wed Feb 14 23:41:19 AEST 1990


Greetings net.land,

  I have a curious question regarding using bitfields and printing the
values contained in them via the printf() function. Say we have the
following definitions:

             long  bit1 : 10;   /* range = -512 to +511 */
    unsigned long  bit2 : 10;   /* range =    0 to 1023 */

  Then say if I do the following:

    bit1 = -1;
    bit2 = -1;

  The results should be:

    bit1 is   -1;   (since its signed)
    bit2 is 1023;   (since its unsigned)

  The problem is that when I try to print the values of these variables:

    printf("Bit1 = %d, Bit2 = %d\n");

  I get:

    "Bit1 = 1023, Bit2 = 1023"

  Does anyone know a switch to use in printf() or any other way I can use
this function to print out the values? I can't even think of a way to cast
a value into a bitfield (or emulate a bit width), in case the assignment of
-1 to the bitfield variable is not working correctly either. (e.g., Trying
to assign value 0xFFFF to a 10 bit variable isn't going to fit right. I
don't think it works as I assigned it to -1 (via requesting the value of -1
from the keyboard) and compared it to -1 it came back false. Probably due
to the bitwidth differences again).

  This came up in a project I have in the background right now. I am trying
to avoid having to write my own printing routine for this. And if the
assignment doesnt work either, that could cause some problems.

  The compiler I'm using is not very smart sometimes, and many things don't
work unless cast correctly (does do SOME autocasting, but not much).

  Any ideas would be appreciated.

  Thanks,

        Darrin Hyrup
--
Darrin A. Hyrup              // AMIGA Enthusiast         rencon!esfenn!dah
magik at sorinc.PacBell.COM   \X/ & Software Developer   pacbell!sorinc!magik
==========================================================================
"Speak little and well, if you wish to be considered as possessing merit."



More information about the Comp.lang.c mailing list