Re: Int Val of Hex From NSData
Re: Int Val of Hex From NSData
- Subject: Re: Int Val of Hex From NSData
- From: David Remahl <email@hidden>
- Date: Tue, 11 Mar 2003 00:25:04 +0100
On Monday, March 10, 2003, at 11:46 PM, Seth Willits wrote:
On Monday, March 10, 2003, at 07:32 AM, Clark S. Cox III wrote:
On Monday, Mar 10, 2003, at 10:05 US/Eastern, Seth Willits wrote:
If I have an NSData object that has three bytes in it (A9B), how can
I get the integer equivalent (2715)?
I'm assuming that you actually mean 3 bytes (and not 3 hex characters)
This should do it:
const unsigned char *bytes = [nsData bytes]
unsigned int value;
NSAssert([nsData length] >= 3);
value = bytes[0] << 16 | bytes[1] << 8 | bytes[2];
I think Clark misinterpreted the original question somewhat...I think
Seth actually wants to convert a hex number (since he writes _three_
bytes - and that would be 6 hex characters.
One way to do this, is to first convert the NSData to NSString using
(initWith
Data:encoding:), and then use NSScanner's -scanHexInt: method
on the resulting NSString.
Another way is to first do something along these lines:
char *hexString = hex[4] = { 0, 0, 0, 0 }; // { 3 characters that will
be filled, and termination }
int num; // this is where the result will be stored (eg 2714)
bcopy([nsData bytes], hex, 3); // move the 3 bytes in question to the
hex char array
sscanf( hex, "x", &num ); // scan for a hexadecimal number
Seriously? Wow... I'm just very used to higher level languages then.
So there isn't any
int = [[NSData subdataWithRange:range] integerValue]6
NSData doesn't respond to integerValue either (since byte ordering etc
is unknown). You can
or what about:
NSString = [[NSData subdataWithRange:range] stringValue]
NSData doesn't respond to stringValue, since there is no way for the
framework to know what encoding you want to use or how to otherwise
interpret the data.
or
[NSData setBytes: NSData atOffset: int length: int]
?? For sure NSData has no setBytes: method. Besides, how ever would
this give the integer value?
Clark's suggestion will work perfectly if you actually want the int
that the data represents as binary.
/ Rgds, David
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.