Melika Barzegaran
Melika Barzegaran

Reputation: 439

What's wrong with the definition of this struct?

I have defined the screen with a struct as below:

struct
{
    private:

    //data and attributes
    char character                  : 8;
    unsigned short int foreground   : 3;
    unsigned short int intensity    : 1;
    unsigned short int background   : 3;
    unsigned short int blink        : 1;

    public:

    unsigned short int row;
    unsigned short int col;

    //a function which gets row, column, data and attributes then sets that pixel of the screen in text mode view with the data given
    void setData (unsigned short int arg_row,
                  unsigned short int arg_col,
                  char arg_character,
                  unsigned short int arg_foreground,
                  unsigned short int arg_itensity,
                  unsigned short int arg_background,
                  unsigned short int arg_blink)
    {
        //a pointer which points to the first block of the screen in text mode view
        int far *SCREEN = (int far *) 0xB8000000;

        row = arg_row;
        col = arg_col;
        character = arg_character;
        foreground = arg_foreground;
        intensity = arg_itensity;
        background = arg_background;
        blink = arg_blink;

        *(SCREEN + row * 80 + col) = (blink *32768) + (background * 4096) + (intensity * 2048) + (foreground * 256) + character;
    }
} SCREEN;

but when I use characters with more than '128' ASCII code in using this struct, data will be crashed. I defined character field with 8 bit. so what's wrong with this definition?

Upvotes: 0

Views: 106

Answers (1)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

In the c++ compiler you use apparently char is signed and so in an 8 bit character you fit values from -128 to 127(assuming two's complements representation for negative values is used). If you want to be guaranteed to be able to fit values greater than or equal to 128, use unsigned char.

Upvotes: 3

Related Questions