2014-01-29 20 views
1

我無法將我設備的ID散列成64位(或更高)的表示形式,然後將其轉換爲基準表 - 31代表。任何人有任何提示或指導?我一直在網上尋找,似乎找不到多少。將設備ID散列成64位(或更高),然後將其轉換爲base-31 [iOS]

每個基-31位應該然後由該列表來表示:2 3 4 5 6 7 8 9 A B C D E F G H J K M N P Q R S T U V W X Y Z

我已經試過:

NSString *myID = [[[UIDevice currentDevice] identifierForVendor]UUIDString]; 
NSLog(@"Non Hash: %@", myID); //Logs the 36 character string 
myID = [NSString stringWithFormat:@"%lu",(unsigned long)[myID hash]]; // Changed thanks to rokjarc 
NSLog(@"Hash: %@", myID); //Logs same 36 character string 


//Logs 36 character string 
NSLog(@"UUIDString: %@", [[[UIDevice currentDevice] identifierForVendor] UUIDString]); 

//Logs out a 10 character numeric value 
NSLog(@"Hash: %lu", (unsigned long)[[[[UIDevice currentDevice] identifierForVendor] UUIDString] hash]); 

//Logs out a 2 character numeric value 
NSLog(@"LongLong: %lld", [[[[UIDevice currentDevice] identifierForVendor] UUIDString] longLongValue]); 
+1

使用'本身份識別碼= [本身份識別碼的散列]; ' - 這個方法不會修改它自己的字符串 - 它會返回字符串的散列... –

+0

@rokjarc好的!它實際上是'myID = [NSString stringWithFormat:@「%lu」,(unsigned long)[myID hash]]'因爲你正在從NSUInteger轉換爲NSString。任何想法如何將其轉換爲基地31 12位數字符串?提前致謝。 – Chris

+1

如果將問題限制爲64位整數,這並不困難。基本上保持數字除以31,並將餘數累加成一個字符串。對於大於整數的數字,事情會變得更加複雜。要麼使用大整數數學包。 – zaph

回答

2

[[[UIDevice currentDevice] identifierForVendor]UUIDString]返回它由32個十六進制字符,其是128一個UUID位。 12個base31字符只能表示63位。因此整個UUID不能被表示。

最好的辦法是通過SHA運行UUID(這似乎是[myID hash]所做的),並將其中的63位轉換爲12個base31字符。

的原因散列函數(SHA)是去除的UUID任何圖案,在SHA的結果每個位是同樣可能是一個1或0。

注: 31^12 = 7.87E17和2^64 = 1.84E19
因此64位數字不能用12個基本31個字符表示。但是63位可以。

對於大於64位的值,Base32是lot比base31更簡單。

下面是從一個64位整數創建的base31字符的字符串一個代碼示例:

uint64_t uid = 14467240737094581; 

NSString *baseCharacters = @"23456789ABCDEFGHJKMNPQRSTUVWXYZ"; 
NSUInteger base = baseCharacters.length; 
NSMutableString *baseString = [NSMutableString new]; 
while (baseString.length < 12) { 
    uint64_t remainder = uid % base; 
    uid /= base; 
    NSString *baseCharacter = [baseCharacters substringWithRange:NSMakeRange(remainder, 1)]; 
    [baseString insertString:baseCharacter atIndex:0]; 
} 
NSLog(@"baseString: %@", baseString); 

的NSLog輸出:
即basestring:2KP7MAR5CX86

+0

令人驚歎!謝謝。我昨天晚上在做一些事情,你的代碼看起來更乾淨清晰。非常感謝! – Chris

相關問題