这个结构的定义有什么问题?

时间:2013-12-09 12:33:13

标签: c++ struct

我已使用如下结构定义了屏幕:

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;

但是当我在使用这个结构时使用超过'128'ASCII码的字符时,数据将会崩溃。我用8位定义了字符字段。那么这个定义怎么了?

1 个答案:

答案 0 :(得分:3)

在你使用的c ++编译器中,显然char是有符号的,因此在8位字符中你可以拟合从-128127的值(假设使用了两个补码表示负值) 。如果您希望保证能够拟合大于或等于128的值,请使用unsigned char。