xHarbour Reference Documentation > Function Reference xHarbour Developers Network  

HB_BitShift()

Shifts bits in a numeric integer value.

Syntax

HB_Bitshift( <nInteger>, <nShift> ) --> nResult

Arguments

<nInteger>
This is a numeric integer value.
<nShift>
This numeric integer value specifies how far to shift bits. When a negative number is passed, bits are shifted to the right. A positive value shifts bits to the left.

Return

The function returns a numeric value. It is the result of the bit-shift operation.

Description

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.

Info

See also:<<, >>, HB_BitIsSet(), HB_BitReset(), HB_BitSet()
Category: Bitwise functions , xHarbour extensions
Source:rtl\hbBitf.c
LIB:xhb.lib
DLL:xhbdll.dll

Example

// 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

Copyright © 2006-2007 xHarbour.com Inc. All rights reserved.
http://www.xHarbour.com
Created by docmaker.exe