0

I need to find a way to convert an arbitrary character typed by a user into an ASCII representation to be sent to a network service. My current approach is to create a lookup dictionary and send the corresponding code. After creating this dictionary, I see that it is hard to maintain and determine if it is complete:

    __asciiKeycodes[@"F1"] = @(112);
    __asciiKeycodes[@"F2"] = @(113);
    __asciiKeycodes[@"F3"] = @(114);
//...
    __asciiKeycodes[@"a"] = @(97);
    __asciiKeycodes[@"b"] = @(98);
    __asciiKeycodes[@"c"] = @(99);

Is there a better way to get ASCII character code from an arbitrary key typed by a user (using standard 104 keyboard)?

Alex Stone
  • 46,408
  • 55
  • 231
  • 407
  • 1
    Please checkout this answer, hopefully it helps a bit. http://stackoverflow.com/questions/2832729/how-to-convert-ascii-value-to-a-character-in-objective-c – Tyler Aug 07 '15 at 18:33
  • In the view receiving the keyboard event override `keyDown(event: NSEvent)` and get the key code from the `keyCode` property of the event. – vadian Aug 07 '15 at 19:07
  • 1
    What do you plan to use for the letter "p"? That should be 112 but you are using that for the F1 key. – rmaddy Aug 07 '15 at 19:24

3 Answers3

1

Objective C has base C primitive data types. There is a little trick you can do. You want to set the keyStroke to a char, and then cast it as an int. The default conversion in c from a char to an int is that char's ascii value. Here's a quick example.

char character= 'a'; NSLog("a = %ld", (int)test);

console output = a = 97 To go the other way around, cast an int as a char;

int asciiValue= (int)97; NSLog("97 = %c", (char)asciiValue);

console output = 97 = a

Alternatively, you can do a direct conversion within initialization of your int or char and store it in a variable.

char asciiToCharOf97 = (char)97; //Stores 'a' in asciiToCharOf97

int charToAsciiOfA = (int)'a'; //Stores 97 in charToAsciiOfA

NSGangster
  • 2,397
  • 12
  • 22
  • Also, ascii is a standardized character set and doesn't include Function keys, your 112 would actually return a p, found this website to explain it and hopefully it will help you or lead you in the right direction if function keys are a must have for your project. [link](http://www.thecodingforums.com/threads/re-ascii-code-for-functions-keys-f1-f12-and-tab-key.277457/) – NSGangster Aug 07 '15 at 19:47
0

This seems to work for most keyboard keys, not sure about function keys and return key.

NSString* input = @"abcdefghijklkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+[]\{}|;':\"\\,./<>?~ ";
for(int i = 0; i<input.length; i ++)
{
    NSLog(@"Found (at %i): %i",i , [input characterAtIndex:i]);
}
Alex Stone
  • 46,408
  • 55
  • 231
  • 407
-1

Use stringWithFormat call and pass the int values.

Lucian Boboc
  • 480
  • 2
  • 6