我只是想知道是否有一種方法可以將位數「移位」? 我已經使用了Google的搜索結果,並且找不到與我想要的有關的任何內容。 假設我有號碼0b01001101,並且我想將它兩次移到右側的「就地」,將所有落在開頭的數字附加到後面。所以它看起來像0b01010011。 C++中是否有任何函數可以讓我左右移位?位移位
位移位
回答
你想實現一個rotational shift
這裏有一個模板化的版本應與所有類型的整型的工作(包括短褲,字符,整型,和無符號/都簽署)。
template<class T>
T rotate_shift_right(T x, int shift)
{
if ((shift > 0) && (shift < (sizeof(x)*8)))
{
x = ((unsigned)x >> shift) | (x << (sizeof(x) * 8 - shift));
}
return x;
}
template<class T>
T rotate_shift_left(T x, int shift)
{
if ((shift > 0) && (shift < (sizeof(x)*8)))
{
x = (x << shift) | (((unsigned)x) >> (sizeof(x) * 8 - shift));
}
return x;
}
不,你應該創建自定義一個
這是真實的,儘管簡約,並回答了這個問題 – ShinTakezou
這實在是一個評論,而不是問題的答案。請使用「添加評論」爲作者留下反饋。 – TemplateRex
@rhalbersma好吧,如果我再次讀到這個問題,我認爲我的帖子實際上是一個答案。也許太短(猜這就是爲什麼2 downvotes),但是是正確的。 – Saphrosit
使用匯編指令回報率和每次應該做的工作得到了進位標誌的值。
int rotate(int x, int n)
{
for(int i = 0; i < n; i++) {
__asm {
ror x, 1 ; rotate and store limit bit in cf
lahf ; get part of flags in ah
and ah, 1 ; get only the cf
shl eax, 31 ; put it at the end
and x, eax ; and store in x
}
}
return x;
}
這是作爲供應商特定的擴展實現的。對於MSVC,您可以使用_rotl8, _rotl16(或_rotr*
向右旋轉)。不確定GCC,但你總是可以下降到裝配,並使用rol
或ror
。
- 1. 移位N位
- 2. 移位位java
- 3. 位列移位
- 4. 位移位
- 5. C位移位奇數結果過去15位移位左移
- 6. 位位移在Java
- 7. 位位移功能,在HSV圖像移位位
- 8. Android位圖移位/移動問題
- 9. 左移位並丟棄位
- 10. 按位移位精度
- 11. VHDL - 將std_logic_vector移位8位
- 12. 位運算,移動進位
- 13. 位位移char數組
- 14. 6502彙編移位位
- 15. C中的逐位移位
- 16. 的Python位位移32位約束
- 17. 在C位移位是我的位?
- 18. 負位數移位的位移符號運算符
- 19. 位移在QGraphicsScene
- 20. C按位移
- 21. 位移x *數
- 22. 移位BitArray
- 23. 指針位移?
- 24. 移位練習
- 25. 移位QBytearray?
- 26. BitArray - 移位
- 27. 按位移 -
- 28. 循環移位
- 29. 拖放移位
- 30. JavaScript位移
術語「循環移位」是你在找什麼? http://stackoverflow.com/questions/776508/circular-shift-operations-in-c而且你可以谷歌這個術語 – Yuf
好吧,我會如何去做我自己的?如果結果是1,我應該把它與1相加,然後右移1,然後用255或者(或者二進制數的大小)進行或運算?類似的左移方法? – Hondros
@Yuf是的,我認爲這正是我正在尋找的! :D – Hondros