Loading...
Logo
Processing Forum

Converting key into integer value

in General Discussion  •  Other  •  4 months ago  
Hey everybody, I've been searching all over for the answer to this, so I hope that by asking it here I will finally get what I am looking for.

I am simply curious if it is possible to convert the value of key to a numerical value.  I figured it might be some sort of ASCII number, but I still can't figure this out.  I know it would be possible with a disgusting amount of if-statements, but I would love to avoid that if at all possible.

Thanks in advance,
-PinSeventy

Replies(5)

you mean


Copy code
  1. void draw(){}
  2. void keyReleased(){
  3.   println(int(key));
  4. }

?

Variable key is already an integral numerical value! More specifically, a data-type char.
Which is an unsigned 16-bit value (0 - 65535 or 2^16 - 1).

However, when a char value is meant to be displayed, rather than its numerical value, 
representation of its  ASCII / Unicode character is shown instead!

That's why a conversion is needed when you want to see its true numerical value.
Usually, an (int) cast operator is the fastest and simple way for it -> println( (int) key );

As long as you don't need negative numbers, and it's confined between 0 - 65535, 
a char variable can use any Java operator as any other type!  
What I got confused is that if you look at a UTF-8 table for, lets say 'a', it will say the code is: 61 or U+0061, but the code above will print 97... which happens to be decimal for hex 61... as I learned in a question at StackOverflow, so you can say:


Copy code
  1. void draw() {
  2. }
  3. void keyReleased() {
  4.   char k = key;
  5.   print("char " + key + " = ");
  6.   print(" decimal " + (int)key + " = ");
  7.   println("hexadecimal " + hex(int(k)) );

  8. }

Java uses UNICODE-16 (UTF-16).
And as I've mentioned above, char is a a fully integral numerical data-type as byte, short, int & long are!

There are 2 peculiarities though:
  1. It's the only Java's unsigned data-type.
  2. It displays itself as Unicode-16 characters.
So, @ line #7, the converters int() function or (int) cast operator are redundant:  
println( "hexadecimal " + hex(key) );


great, thanks :)