开发者

How to produce an NSString with format HxHHHHHHHH representing a float value in Objective C, C++, or C?

Suppose we have

float x = 24.0;

I want to do the following:

// hexRepresentation is of format HxHHHHHHHH 
// where H is a hexadecimal symbol 0-9 or a-f
NSString *hexRepresentation = [self hexadecimalFromFloat:x];

Pl开发者_JS百科ease help me complete the following method:

- (NSString *)hexadecimalFromFloat:(float)flt {
    NSString *h;
    /*
        What should I do here to convert the float
        value into its HxHHHHHHHH format? Then what
        should I do to ensure it's converted into a
        proper NSString and assigned to h?
     */
    return h;
}


You can get the machine data of a float either by using a union, or by casting a pointer and dereferencing. A union is used when multiple types could be stored in one location, and any of those types can be accessed no matter which was used to set the value.

union {
    float f;
    unsigned int i;
} converter;
converter.f = flt;
// converter.i now contains an integer representing the hexadecimal value of flt
h = [NSString stringWithFormat:@"0x%08X",converter.i];

If you get the pointer to the float and then cast it to an integer, you get the same effect. This method takes less code, but can be more confusing when you see it.

h = [NSString stringWithFormat:@"0x%08X",*((unsigned int *)(&flt))];

Just like Yann's answer, the result is the machine's representation of the float, and this code assumes a float and int are both 4 bytes long.


Rough, untested code:

unsigned int *fp = (unsigned int*)&flt;
h = [NSString stringWithFormat:@"0x%08X", *fp];

This may or may not be in IEEE-754 notation, etc etc. It also assumes sizeof(float) == sizeof(int) == 4

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜