2011-08-24 97 views
3

翻一番我有這樣的代碼在Java中:如何轉換十六進制在iphone

String pr = "4173df24c969ff63" 
    long prLongBits = Long.valueOf(pr, HEX_BASE).longValue(); 
    prDoubleValue = Double.longBitsToDouble(prLongBits); 

的結果:prDoubleValue = 2.083694058837832E7

我將如何轉換這個目標C? 我試圖從十六進制轉換爲長,然後長到雙,但沒有適當的結果。

BR,

Suppi

回答

3

我會嘗試像下面這樣:

// Read the hex string into a 64-bit integer 
unsigned long long doubleBits; 
double result; 
NSScanner *scanner = [NSScanner scannerWithString:@"4173df24c969ff63"]; 
if ([scanner scanHexLongLong:&doubleBits]) { 
    memcpy(&result, &doubleBits, sizeof(result)l 
} 

我還沒有嘗試過了,但基本的思路應該是近似直角。您希望將十六進制字符串轉換爲以適當大小的數字數據類型存儲的一堆字節。一旦該位模式在內存中,我們將其複製到分配給雙精度的內存中。

這假定用於創建十六進制字符串的字符串表示形式使用與您的代碼運行時相同的字節順序。

+0

謝謝一噸,這似乎工作正常.... – Suppi

0

你的問題有點含糊不清,但我相信你想解釋字符串作爲double的編碼。這裏有一種方法可以做到這一點:

#include <string.h> 
#include <stdint.h> 
#include <inttypes.h> 
#include <stdio.h> 

double interpretAsDouble(const char *string) { 
    // convert the string to a 64-bit int ... 
    uint64_t encoding; 
    sscanf(string, "%"SCNx64, &encoding); 
    // ... then interpret that 64-bit int as the encoding of a double. 
    double value; 
    memcpy(&value, &encoding, sizeof value); 
    return value; 
} 

int main(int argc, char *argv[]) { 
    printf("%g\n", interpretAsDouble("4173df24c969ff63")); 
    return 0; 
} 
相關問題