2011-07-20 14 views
0

假設我們有如何生成一個格式爲HxHHHHHHHH的NSString,表示Objective C,C++或C中的浮點值?

float x = 24.0; 

我要做到以下幾點:

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

請幫我完成了以下方法:

- (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; 
} 

回答

1

粗糙,未經測試的代碼:

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

這可能是也可能不是IEEE-754符號等等。它也假定爲sizeof(float) == sizeof(int) == 4

+0

不,這會將浮點數四捨五入爲整數並打印出該整數的十六進制表示形式。 –

+0

@Adam Rosenfield這是好的 - 是的,當你投射到unsigned int時,小數點右邊的東西會被切斷,但你總是可以用16或10的冪乘原始的浮點數,然後解釋轉換後的數值;當然,還有那些令人討厭的2的讚美,但它是我主要以後的格式...畢竟它是一個有限的世界 –

+0

@Adam:談論大腦凍結 - 修復! –

3

您可以通過使用聯合或通過投射指針和取消引用來獲取float的機器數據。當多個類型可以存儲在一個位置時使用聯合,並且可以訪問這些類型中的任何一個,而不管用於設置值。

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]; 

如果您得到指向float的指針,然後將其轉換爲整數,則會得到相同的效果。這種方法只需要較少的代碼,但當你看到它時會更困惑。

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

就像晏的回答,結果是浮動的機器的表現,而這代碼假定一個float和INT長都4個字節。