keyPressed is behaving very oddly

This is going to be something dumb but…

I have a code snipet showing my issue.

int currentRow;
void setup() {
}
void draw() {
}

void keyPressed() {
  currentRow =  key;
  println(key);
  println(currentRow);
}

If I run the avove code and press the number 5 I get
5
53
in the console

If I run

int currentRow;

void setup() {
}
void draw() {
}

void keyPressed() {
  currentRow =  key-48;
  println(key);
  println(currentRow);
}

I get
5
5
in the console…
Why oh why do I need the -48 for this to work. It seems to be a difference between the key and the keyCode but I make no reference to the keyCode.

I can Obvs work around it but my internal OCD won’t let it lie.

Thanks

1 Like

Field PApplet::key is of datatype char:

While field PApplet::keyCode is of datatype int:

Even though a char is an unsigned 16-bit (2-byte) integer datatype, when it’s converted to a String (for example, when we use println() on it) its numerical value is converted to a UTF-16 character representation.

Notice that Java’s minimum datatype for math calculation is the signed 32-bit (4-byte) int datatype.

So when we have an expression like this key - 48, or even such as this key - ‘0’, both operands are coerced up to datatype int before it proceeds w/ the operator - minus.

If you hit the key 5, field key will contain the value '5', which when converted to int becomes 53.

Therefore key - 48 is coerced to 53 - 48.
The same case for key - ‘0’, which is coerced to 53 - 48 as well.

3 Likes

Thanks for the speedy info, that sounds like a lot of coercion :slight_smile:
Will have a review of the attached docs. It had me confused for a while TBH.

That’s the ASCII value by the way

0 being 48 in Ascii etc.

2 Likes