你可以使用整數除法(\
)和按位AND(AND
)做到這一點。
DIM x(0 TO 3) AS _UNSIGNED _BYTE
a& = &HCEED6644&
x(0) = (a& AND &HFF000000&) \ 2^24
x(1) = (a& AND &H00FF0000&) \ 2^16
x(2) = (a& AND &H0000FF00&) \ 2^8
x(3) = a& AND &HFF&
PRINT HEX$(x(0)); HEX$(x(1)); HEX$(x(2)); HEX$(x(3))
需要注意的是,你可以選擇使用一個通用RShift~&
函數,而不是原始整數除法,因爲你真的做什麼換擋位:
x(0) = RShift~&(a& AND &HFF000000&, 18)
...
FUNCTION RShift~& (value AS _UNSIGNED LONG, shiftCount AS _UNSIGNED BYTE)
' Raise illegal function call if the shift count is greater than the width of the type.
' If shiftCount is not _UNSIGNED, then you must also check that it isn't less than 0.
IF shiftCount > 32 THEN ERROR 5
RShift~& = value/2^shiftCount
END FUNCTION
在該大廈,您可以創建另一個功能:
FUNCTION ByteAt~%% (value AS _UNSIGNED LONG, position AS _UNSIGNED BYTE)
'position must be in the range [0, 3].
IF (position AND 3) <> position THEN ERROR 5
ByteAt~%% = RShift~&(value AND LShift~&(&HFF&, 8*position), 8*position)
END FUNCTION
注意的是使用一個LShift~&
函數(由2的冪乘)轉移位到左側。一個潛在的更好的替代方法是首先執行右移,只是掩模的低8位,從而消除了LShift~&
的需要:
FUNCTION ByteAt~%% (value AS _UNSIGNED LONG, position AS _UNSIGNED BYTE)
'position must be in the range [0, 3].
IF (position AND 3) <> position THEN ERROR 5
ByteAt~%% = RShift~&(value, 8*position) AND 255
END FUNCTION
順便提及,另一種已知的作爲FreeBASIC QB樣實現具有實際SHR
操作者,像MOD
或AND
一樣使用,以直接執行移位操作而不是使用可能更快的分割。
你也可以使用QB64的DECLARE LIBRARY
設施,以創建在C++中,將進行移位操作功能:
/*
* Place in a separate "shift.h" file or something.
*/
unsigned int LShift (unsigned int n, unsigned char count)
{
return n << count;
}
unsigned int RShift (unsigned int n, unsigned char count)
{
return n >> count;
}
下面是完整的相應QB64代碼:
DECLARE LIBRARY "shift"
FUNCTION LShift~& (value AS _UNSIGNED LONG, shiftCount AS _UNSIGNED _BYTE)
FUNCTION RShift~& (value AS _UNSIGNED LONG, shiftCount AS _UNSIGNED _BYTE)
END DECLARE
x(0) = ByteAt~%%(a&, 0)
x(1) = ByteAt~%%(a&, 1)
x(2) = ByteAt~%%(a&, 2)
x(3) = ByteAt~%%(a&, 3)
END
FUNCTION ByteAt~%% (value AS _UNSIGNED LONG, position AS _UNSIGNED BYTE)
'position must be in the range [0, 3].
IF (position AND 3) <> position THEN ERROR 5
ByteAt~%% = RShift~&(value, 8*position) AND 255
END FUNCTION
如果QB64已文檔化的API當移位計數過高時,可能會從C++代碼中引發QB64錯誤,而不是依賴C++的行爲來實質上忽略太高的移位計數。不幸的是,事實並非如此,它可能會導致更多的問題而不是價值。
哦,謝謝!這可能是我見過的最詳細的答案! – Aureal