2009-05-05 53 views

回答

18

嘗試使用以下

public long MakeLong(int left, int right) { 
    //implicit conversion of left to a long 
    long res = left; 

    //shift the bits creating an empty space on the right 
    // ex: 0x0000CFFF becomes 0xCFFF0000 
    res = (res << 32); 

    //combine the bits on the right with the previous value 
    // ex: 0xCFFF0000 | 0x0000ABCD becomes 0xCFFFABCD 
    res = res | (long)(uint)right; //uint first to prevent loss of signed bit 

    //return the combined result 
    return res; 
} 
+0

呃,難道不應該是: long res = left; res =(res << 32) res | = right; return res; ?? – ParoXoN 2009-05-05 22:49:58

+0

我認爲你的意思是(res << 32)以上。 – 2009-05-05 22:50:42

5

嘗試

(long)(((long)i1 << 32) | (long)i2) 

此移動第一INT由32位(int的長度),則在第二INT ORS左,所以你最終將兩個整體連接在一起。

2

這應該做的伎倆

((Int64) a << 32 | b) 

ab是的Int32。儘管您可能想檢查最高位發生了什麼。或者把它放在「unchecked {...}」塊中。

2

要小心這樣擺弄,雖然因爲你會在小端/大端機器上出現問題(exp單聲道平臺並不總是小端)。另外你必須處理符號擴展。在數學上,以下內容是相同的,但涉及符號擴展並且是平臺不可知的。

return (long)(high * uint.MaxValue) + low; 

當在運行時發生抖動時,它會導致性能類似於旋轉位。這是關於解釋型語言的好事之一。

6

只是爲了清晰...雖然接受的答案似乎工作正常。所有提交的襯裏都不會產生準確的結果。

這裏是一個班輪,做工作:

long correct = (long)left << 32 | (long)(uint)right; 

下面是一些代碼,所以你可以測試一下自己:

long original = 1979205471486323557L; 
int left = (int)(original >> 32); 
int right = (int)(original & 0xffffffffL); 

long correct = (long)left << 32 | (long)(uint)right; 

long incorrect1 = (long)(((long)left << 32) | (long)right); 
long incorrect2 = ((Int64)left << 32 | right); 
long incorrect3 = (long)(left * uint.MaxValue) + right; 
long incorrect4 = (long)(left * 0x100000000) + right; 

Console.WriteLine(original == correct); 
Console.WriteLine(original == incorrect1); 
Console.WriteLine(original == incorrect2); 
Console.WriteLine(original == incorrect3); 
Console.WriteLine(original == incorrect4); 
相關問題