xHarbour Reference Documentation > Function Reference |
Shifts bits in a numeric integer value.
HB_Bitshift( <nInteger>, <nShift> ) --> nResult
The function returns a numeric value. It is the result of the bit-shift operation.
Function HB_BitShift() shifts the bits of a numeric integer to the left or the right, depending on the sign of <nShift>.
A shift operation involves all bits of <nInteger>. When the bits are shifted one place to the left, the most significant, or highest, bit is discarded and the least significant (or lowest) bit is set to 0. When the bits are shifted one place to the right, the lowest bit is discarded and the highest bit is set to 0.
A numeric value has 32 bits on a 32 bit operating system.
See also: | <<, >>, HB_BitIsSet(), HB_BitReset(), HB_BitSet() |
Category: | Bitwise functions , xHarbour extensions |
Source: | rtl\hbBitf.c |
LIB: | xhb.lib |
DLL: | xhbdll.dll |
// The example displays the result of bit-shift operations to // the left and the right with the aid of a user defined function // Num2Bit(). Note that the initial integer has only one bit set. // This bit "drops off" when shifted 3 places to the right. PROCEDURE Main LOCAL nInt := 4 LOCAL i, n ? "Original:", " ", Num2Bit( nInt ), Str( nInt, 4 ) ? FOR i:= -3 TO 3 n := HB_BitShift( nInt, i ) ? "Shifted :", Str(i,2), Num2Bit( n ), Str( n, 4 ) NEXT ** output // Original: 00000100 4 // Shifted : -3 00000000 0 (bit dropped off) // Shifted : -2 00000001 1 // Shifted : -1 00000010 2 // Shifted : 0 00000100 4 // Shifted : 1 00001000 8 // Shifted : 2 00010000 16 // Shifted : 3 00100000 32 RETURN FUNCTION Num2Bit( nNumber ) LOCAL nInt := Int( nNumber ) LOCAL nLen := 7 LOCAL cBin := Replicate( "0", nLen+1 ) LOCAL nPos FOR nPos := 0 TO nLen IF HB_BitIsSet( nInt, nPos ) cBin[ nLen-nPos+1 ] := "1" ENDIF NEXT RETURN cBin
http://www.xHarbour.com