views:

397

answers:

2

Hi everybody !

Can someone help me ? I have a NSString with @"12.34" and I want to convert it into a NSString with the same float number but in single precision 32bits binary floating-point format IEEE-754 : like @"\x41\x45\x70\xa4" (with hexa characters) or @"AEp¤"... I'm sure it's something easy but after many hours of reading the doc without finding a solution...

Thank you !

A: 

If you want to get the raw bytes of a float, you could cast it, like so:

NSString *str = @"12.34";
float flt = [str floatValue];
unsigned char *bytes = (unsigned char *)&flt;
printf("Bytes: %x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);

However the order in which these bytes are stored in the array depends on the machine. (See http://en.wikipedia.org/wiki/Endianness). For example, on my Intel iMac it prints: "Bytes: a4 70 45 41".

To make a new NSString from an array of bytes you can use initWithBytes:length:encoding:

mkrause
It's not a good idea to put an arbitrary byte sequence into an `NSString`, because an `NSString` doesn't keep a byte sequence as is, it might apply a change of encodings internally, which might destroy the byte sequence without changing textual representation. And I'm not sure if an `NSString` can contain `\x00`. I would recommend to use NSData instead.
Yuji
+1  A: 

As Yuji mentioned, it's not a good idea to encode an arbitrary byte sequence into an NSString(although it can contain null bytes), as encoding transformations can(and probably WILL) destroy your byte sequence. If you want access to the raw bytes of a float, you may want to consider storing them as an NSData object(though I suggest you think through your reasons for wanting this first). To do this:

NSString *string = @"10.23";
float myFloat = [string floatValue];
NSData *myData = [[NSData alloc] initWithBytes:&myFloat length:sizeof(myFloat)];
Mike
Stephen Canon
Thank you Mike ! I have now to invert the byte sequence ! Someone has an idea ?
LeBelge
Have done that with a ´NSMutableData´ and a ´for´ loop.
LeBelge