0

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 !

4

2 回答 2

1

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)];
于 2009-12-29T23:14:43.297 回答
0

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:

于 2009-12-29T17:42:42.290 回答