Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Bit operations Lib
#1
New Lib so we can use bit operations.


Attached Files
.n7   bit_ops.n7 (Size: 1.62 KB / Downloads: 5)
Reply
#2
That's a new one for me. Bit operations?
Logic is the beginning of wisdom.

Live long and prosper.
Reply
#3
Here's a sample.

Update the lib cause it was not the lastest version. 
Code:
include "bit_ops.n7"

function hex_digit(value)
    if value < 10
        return str(value)
    elseif value = 10
        return "A"
    elseif value = 11
        return "B"
    elseif value = 12
        return "C"
    elseif value = 13
        return "D"
    elseif value = 14
        return "E"
    else
        return "F"
    endif
endfunc

function value_to_hex(value)
    if value < 0
        value = 0
    endif

    if value = 0
        return "0x0"
    endif

    digits = ""
    temp = value

    while temp > 0
        rem = temp % 16
        digits = hex_digit(rem) + digits
        temp = int(temp / 16)
    wend

    return "0x" + digits
endfunc

function value_to_binary(value, bitCount)
    result = ""

    for i = 0 to bitCount - 1
        shift = bitCount - 1 - i
        currentBit = bit_and(bit_shr(value, shift), 1)

        if currentBit = 1
            result = result + "1"
        else
            result = result + "0"
        endif
    next

    return result
endfunc

set window "Bit Panel Demo", 900, 360
set redraw off
cls

value = 48879
bitCount = 16

set color 255, 255, 255
draw rect 0, 0, 900, 360, true

set color 0, 0, 0
set caret 30, 20
wln "Decimal: " + value
set caret 30, 40
wln "Hex: " + value_to_hex(value)
set caret 30, 60
wln "Binary: " + value_to_binary(value, bitCount)

startX = 30
startY = 110
cellW = 28
cellH = 42

for i = 0 to bitCount - 1
    shift = bitCount - 1 - i
    currentBit = bit_and(bit_shr(value, shift), 1)

    x = startX + i * cellW
    y = startY

    if currentBit = 1
        set color 0, 255, 0
    else
        set color 160, 160, 160
    endif

    draw rect x, y, x + 18, y + cellH, true

    set color 0, 0, 0
    set caret x + 2, y + cellH + 8
    if currentBit = 1
        wln "1"
    else
        wln "0"
    endif

    set caret x + 2, y + cellH + 28
    bitLabel = "b" + (bitCount - 1 - i)
    wln bitLabel
next

redraw

while keydown(0) = 0
    fwait 60
wend
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)