简体   繁体   中英

Using 'char' variables in bit operations

I use XLookupString that map a key event to ASCII string, keysym, and ComposeStatus.

int XLookupString(event_structure, buffer_return,  bytes_buffer, keysym_return, status_in_out)

XKeyEvent *event_structure;
char *buffer_return; /* Returns the resulting string (not NULL-terminated). Returned value of the function is the length of the string. */
int bytes_buffer;
KeySym *keysym_return;
XComposeStatus *status_in_out;

Here is my code:

char mykey_string;
int arg = 0;

------------------------------------------------------------

    case KeyPress:
        XLookupString( &event.xkey, &mykey_string, 1, 0, 0 );
        arg |= mykey_string;

But using 'char' variables in bit operations, sign extension can generate unexpected results. I is possible to prevent this?

Thanks

char can be either signed or unsigned so if you need unsigned char you should specify it explicitly, it makes it clear to those reading you code your intention as opposed to relying on compiler settings.

The relevant portion of the c99 draft standard is from 6.2.5 Types paragraph 15 :

The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM