cinputasciikeycode

Is `0x1F` an ASCII scan code, and if so, how is it repeatable?


I am writing a CLI text editor in c. I have to handle a lot of CTRL+key inputs. Right now, I am using a macro that gets the key you want to pair with CTRL, like this: #define CTRL(key) ((key) & 0x1F) and this works, but I don't know exactly how 0x1F represents CTRL.

I think that 0x1F is some type of ASCII scan code (At least that's what I have found), but I don't really know for a fact, and I can't find a table of other keys that follow the same pattern.

What is 0x1F and do similar codes apply to other keys like ALT or ENTER? Does anyone have a table that shows the codes for other special keys?


Solution

  • If you look at the ASCII table:

    ASCII table

    You'll see that the first 32 codes (0x0 - 0x1F) are control characters. That's where 0x1f is coming from. The macro you showed strips off all but the lowest-order 5 bits to result in a value in the control character range.

    The upper case characters are in the 5th and 6th rows. Using the bitmask (key) & 0x1F essentially results in a value that is in the same column and 4 rows up. That gives you the control character that pressing CTRL with that letter will give you.

    Note also that there are other characters that when pressed with CTRL will give you a control character such as @ or [.