0

Im using the following code to send a hex string to an NSStreamoutput:

uint8_t mirandaroutecommand[] = { 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x30, 0x14 };    
NSData *data = [[NSData alloc] initWithBytes:mirandaroutecommand length:sizeof(mirandaroutecommand)];
[hextooloutputStream write:[data bytes] maxLength:[data length]];

This works great but the problem is I need these hex values to come from NSTextfields on the user interface. I've tried to convert the NSTextfield data to an integer but that didn't work. Is there a way to use data from several NSTextfields to build an array of integers using hex values?

I've tried to find an existing topic covering this but I've had no luck.

Ulooky
  • 5
  • 3
  • It's certainly possible. Can you describe what problem you're having converting NSTextfield data to an integer? – user1118321 Jan 23 '12 at 16:31
  • When I convert it to an integer it doesn't remain as a hex value. For instance if I enter 0x03 into my NSTextfield and then convert it into an integer, when I display the result it is empty. If I put a number in NSTextfield like 4 it converts to an integer and displays correctly. Obviously I don't understand how to deal with hex values properly. – Ulooky Jan 23 '12 at 16:49
  • Generally, you don't want users to have to enter hex values, as most users don't understand them. But if this is some technical tool, maybe it's acceptable or desired. If that's the case, you can convert from hex by removing the "0x" from the start of the string (and any whitespace), and then use something like described [here](http://stackoverflow.com/questions/10324/how-can-i-convert-a-hexadecimal-number-to-base-10-efficiently-in-c). But in general, having users entered formatted numbers is not usually a great idea. You might look into other ways to get the data such as steppers or popups. – user1118321 Jan 23 '12 at 17:55
  • Yes this is for use as a technical tool so I do need to have it entered as hex. I looked at the example you linked to and I tried the code. It is converting the hex but I don't want to convert it. I want to use the entered data as hex not as some other base. Any thoughts? – Ulooky Jan 23 '12 at 18:41
  • If you use strtol, as described, the resulting int that it returns will be the value you want. – user1118321 Jan 23 '12 at 19:21

1 Answers1

0

The NSString methods integerValue and intValue assume a decimal representation and ignore and trailing gumph - so apply them to @"0x01" and they see 0 followed by some gumph (x01) which they ignore.

To read a hex value use NSScanner's scanHexInt: (or scanHexLongLong:):

unsigned scannedHexValue;
if ([[NSScanner scannerWithString:textFieldContents] scanHexInt:&scannedHexValue])
{
   // value found
   ...
}

NSScanner is more powerful than just parsing a single value, so with the appropriate method calls you can scan a comma separated list of hex values if you wish.

CRD
  • 52,522
  • 5
  • 70
  • 86