2012-05-03 23 views
0

如何從長N位獲取int和cout(並獲得可讀的int)? 我嘗試如何從長的N位獲取int和cout(並獲得可讀的int)?

int count = sizeof(long) - sizeof(int); 
    int int_val =(long_val>> (sizeof(long) - count)); 

但得到一些horible COUT ......我該怎麼辦 - 如何從長N位切得到一個int和清點它(並獲得可讀INT)?

+1

假設「長」比「int」長(whi ch是一個不好的假設;他們往往是相同的長度),你想要哪些位:高位或低位? –

+0

請注意,您的移動金額爲sizeof(l) - (sizeof(l) - sizeof(i))';如果long是64位,int是32位,即32。如果'long'和'int'都是32位,結果是_still_'32'。但在後一種情況下,感覺不對...... – sarnold

+0

[你在這裏試圖解決的根本問題是什麼?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-問題) – Johnsyweb

回答

0

爲了獲得較低N位,儘量(long_val & ((1<<(N-1)) - 1))

0

有兩個問題與原代碼:

  1. sizeof操作符與字節臺,但>>運營商可與單位

  2. 您正在改變sizeof(long) - sizeof(long) + sizeof(int),這隻能是偶然的改正。

如果你想在一個可移植的方式低位字節,可以使用:

unsigned int_val = (unsigned) (long_val & UINT_MAX); 
1

試試下面的(未優化):

#include <limits> 
#include <iostream> 

using namespace std; 

int lowerBits(long in) { 
    // use unsigned so that sign bit is not propagated 
    // when compiler casts it to a long 
    return in & (unsigned) -1; 
} 

int upperBits(long in) { 
    return lowerBits(in >> numeric_limits<unsigned int>::digits); 
} 

int main(int, char **) { 
    cout << hex << lowerBits(0x4321432112341234) << endl; 
    cout << hex << upperBits(0x4321432112341234) << endl; 
} 

輸出上64位機器,使用gcc:

12341234 
43214321