Bryan ORTIZ
Bryan ORTIZ

Reputation: 316

NSString value as NSData output

I have a NSString which is @"15".

I want my NSData to be 15 also. I know how to convert it to get the value 31 35 but I would like my NSData to be 15 if I use NSLog on it. I'm not asking for a conversion but more for a translation. I don't wanna change the NSLog print but the NSData value. Is there anyway to do it ?

Upvotes: 1

Views: 70

Answers (2)

trojanfoe
trojanfoe

Reputation: 122391

Parse the string to an integer (lets assume a signed 32-bit integer):

NSString *str = @"15";
int32_t i = (int32_t)[str intValue];

To encode it in native endian:

NSData *data = [NSData dataWithBytes:&i length:sizeof(i)];

Note: if you intend to transmit that data to another computer then you need to decide on a common endianness of primitive types. Big endian is traditionally used and facilitated with functions like htonl(), ntohl(), etc. If the computers are all the same platform then you can use the native endianness, for a slight performance boost and code simplification.

Upvotes: 2

Lou Franco
Lou Franco

Reputation: 89172

You need to convert the string to a byte first (by parsing it). Then you can build the NSData from the byte.

Upvotes: 1

Related Questions