0

My problem is this:

I would like to take an NSString (from the user) containing a representation of "HEX" values:

NSString * stringHEX = @"FF00";    //User provided "HEX" as an NSString

...I would then like to insert these exact values into an NSData object. This is where I am having trouble. By using any "dataUsingEncoding" the information from the NSString gets converted to the HEX values OF the NSString information:

NSString * stringHEX = @"FF00";
NSData * dataToSend;
dataToSend = [[NSData alloc] initWithData:[stringHEX dataUsingEncoding:NSUTF8StringEncoding]];

dataToSend now contains: "46463030" and not the "FF00". I understand why this is happening - as I am encoding the NSString values into it's own HEX representation via encoding.. however I can't figure out how to get that string directly across... PUZZLED.

I have tried many different variations. Nothing seems to work. I can get the values I want into NSData by doing something like this:

Byte dataBytes[] = {0xFF,0x00};
NSData * dataToSend;
dataToSend = [[NSData alloc] initWithBytes:dataBytes length:2];

That works and loads what I expect into NSData "FF00".

However - I really need to take user input as NSString and then translate that down into the NSData object....

Any suggestions appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    Why is it puzzling? The UTF8 encoded version of "FF00" is `{'F','F','0','0'}` or `{ 46, 46, 30, 30 }`. You need to *convert* the hexadecimal-encoded *text representation* of the number into the corresponding *integer* and then use the appropriate bit/byte-wise representation of that - not the string! – user2864740 Nov 13 '13 at 04:13
  • See http://stackoverflow.com/questions/1874910/convert-hex-string-to-long (although this doesn't say how to get it directly into NSData). – user2864740 Nov 13 '13 at 04:15

0 Answers0