Objective-C Converting an integer to a hex value

DavidAndroidDev picture DavidAndroidDev · Mar 29, 2011 · Viewed 29.2k times · Source

I've got a dictionary initialized like so...

keyDictionary = [[NSDictionary dictionaryWithObjects:values forKeys:keys]retain];

where keys is an NSArray of the alphabet and other characters and values is an NSArray of unsigned chars, which are the USB hex keycodes for those characters.

The USB key codes are hex values that range from 0x04 to 0xE7. I'm trying to create a map between these two depending on what key is pressed on the keyboard.

The values array is created like so...

NSArray *values = [NSArray arrayWithObjects: 
                  [NSNumber numberWithUnsignedChar:0x04]/*A*/,
                  [NSNumber numberWithUnsignedChar:0x05]/*B*/, /*ETC*/]; 

So ideally when I run this code... where character == @"I"

- (uint8) getUSBCode:(NSString *)character
{
    NSNumber *val = [keyDictionary objectForKey:character];

    return (uint8)[val unsignedCharValue];
}

I would expect to get back 0x0C, but I'm getting 12 back as an int (which after I thought about it, makes sense). I need the hex value preserved. I do NOT need a string value. I need a straight conversion to the hex value or a better way to store

uint8 is just a typedef unsigned char.

EDIT I was not clear when I posted this earlier. Here's what I need.

I need the hex value of these codes because they are being sent over the internal company network. In addition, the pressed key's value is being converted from big endian (or little, it's escaping me right now which one it is) to the other, then being transmitted over an internal network. I understand that these values are stored in binary, but I need to transmit them in hex.

Also, I stated I was getting 12 back from the function. I was reading 12 from the debugger, not actually getting the value. That might be why I was getting confused.

Answer

JeremyP picture JeremyP · Mar 29, 2011

12 (in base 10) is 0x0c.

If you want to print it out in hex, use the %x format specifier e.g.

NSLog(@"Hex value of char is 0x%02x", (unsigned int) c);

If you want to see it in hex in the debugger (assuming Xcode 3.2.x) right click on the variable and select hexadecimal as the format.