Sign in to follow this  
Followers 0
Yashied

Bit Operations

2 posts in this topic

func _GetBit($iValue, $iPos, $iCount = 1)
    if ($iPos < 0) or ($iCount <= 0) then
        return 0
    endif
    
    local $iMask = 0
    
    for $i = 1 to $iCount
        $iMask = BitShift($iMask, -1) + 1
    next
    return BitAND(BitShift($iValue, $iPos), $iMask)
endfunc; _GetBit

func _SetBit($iValue, $iPos, $iBit, $iCount = 1)
    if ($iPos < 0) or ($iCount <= 0) then
        return $iValue
    endif
    
    local $iMask = 0
    
    for $i = 1 to $iCount
        $iMask = BitShift($iMask, -1) + 1
    next
    $iMask = BitShift($iMask, -$iPos)
    if $iBit = 0 then
        return BitAND($iValue, BitXOR($iMask, 0xFFFFFFFF))
    else
        return BitOR($iValue, $iMask)
    endif
endfunc; _SetBit

func _InvBit($iValue, $iPos, $iCount = 1)
    if ($iPos < 0) or ($iCount <= 0) then
        return $iValue
    endif
    
    local $i
    
    for $i = 1 to $iCount
        $iValue = _SetBit($iValue, $iPos + ($i - 1), 1 - _GetBit($iValue, $iPos + ($i - 1)))
    next
    return $iValue
endfunc; _InvBit

func _BitToStr($iValue, $iPos = 0, $iCount = 32)
    if ($iPos < 0) or ($iCount <= 0) then
        return ''
    endif
    
    local $i, $t = ''
    
    for $i = 1 to $iCount
        $t = _GetBit($iValue, $iPos) & $t
        $iPos += 1
    next
    return $t
endfunc; _BitToStr

func _StrToBit($sString)
    
    local $i, $b, $ret = 0, $n = StringLen($sString)
    
    for $i = 1 to $n
        $b = StringRight($sString, 1)
        if ($b <> '0') and ($b <> '1') then
            return ''
        endif
        $ret = _SetBit($ret, $i - 1, ($b = '1'))
        $sString = StringTrimRight($sString, 1)
    next
    return $ret
endfunc; _StrToBit

Examples

_SetBit(0x0F, 5, 1, 2) ; 00001111b (0x0F) => 01101111b (0x6F)

_GetBit(0x6F, 4, 4) ; 01101111b (0x6F) => 0110b (0x6)

_InvBit(0x6F, 0, 4) ; 01101111b (0x6F) => 01100000 (0x60)

_BitToStr(0x6F, 4, 4); 01101111b (0x6F) => "0110"

_StrToBit("01101111") ; "01101111" => 0x6F

:D

Share this post


Link to post
Share on other sites



Thank you very much! :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0