Golang如何将十进制转为定长二进制字符串?

问题描述 投票:0回答:2

我正在写一个 CHIP-8 模拟器,我正在努力编写 DXYN 操作码,它根据 uint8 位代码绘制精灵 1 使像素变白 0 使它变黑,只有在有办法将 8 位整数转换为固定大小(8 位)的字符串,那么它可能会起作用。

    // DXYN - Draws a sprite at coordinate (VX, VY) that has a width of 8 pixels and a height of N pixels.
    // Each row of 8 pixels is read as bit-coded starting from memory location I.
    // I value does not change after the execution of this instruction. 
    // As described above, VF is set to 1 if any screen pixels are flipped from set to unset when the sprite is drawn, and to 0 if that does not happen
    if ByteCode[0] == 'd' {
        vx := hexToInt(ByteCode[1:2])
        vy := hexToInt(ByteCode[2:3])
        h := hexToInt(ByteCode[3:])

        fmt.Println(vx, vy, h)
//        os.Exit(0)

        // Render sprite starting from (vx, vy) each row is 8 pixel wide
        // Row pixels are bit-coded 1 is white 0 is black 
        for i:=0; i < int(h); i++ {
            
            BitString := strconv.FormatUint(uint64(Memory[I+uint16(i)]), 2)

            fmt.Println(BitString)
//           os.Exit(0)
            
            // Render individual row pixel by pixel
            // If there is a different color on the screen VF is set to 1 otherwise its set to 0
            for j:=0; j < 8; j++ {

                if string(BitString[j]) == "0" {

                    if Screen[V[vx]+uint8(j)][V[vy]+uint8(i)] == 1 {
                        V[15] = 1
                    } else {
                        V[15] = 0
                    }

                    Screen[V[vx]+uint8(j)][V[vy]+uint8(i)] = 0

                } else if string(BitString[j]) == "1" {

                    if Screen[V[vx]+uint8(j)][V[vy]+uint8(i)] == 0 {
                        V[15] = 1
                    } else {
                        V[15] = 0
                    }

                    Screen[V[vx]+uint8(j)][V[vy]+uint8(i)] = 1

                }

            }

        }

    }

我尝试用其他语言实现解决方案,但在网上找不到任何适用于 Golang 的东西。

go type-conversion emulation bitstring chip-8
2个回答
0
投票

执行:

str:=fmt.Sprintf("%08b",number)

感谢 Burak Serdar 帮我解决了这个问题。


0
投票

XY 问题是询问您尝试的解决方案而不是您的实际问题:XY 问题.


我尝试用其他语言实现解决方案。

您将位转换为字符串值。

你实现了

str:=fmt.Sprintf("%08b",number)

fmt 包使用运行时反射,以解释器速度运行。


一个简单的编译 Go 函数,将位转换为字符串。

func BitString(d uint8) string {
    var b [8]uint8
    for i := len(b) - 1; i >= 0; i-- {
        b[i] = '0' + d&1
        d >>= 1
    }
    return string(b[:])
}

Go 具有编译时整数按位逻辑和移位运算符。

对于您的代码,Go 编程语言解决方案可能看起来更像这样(未经测试)

for i := 0; i < int(h); i++ {
    bits := Memory[I+uint16(i)]
    for j := 0; j < 8; j++ {
        bit := bits >> ((8 - 1) - j) & 1
        if Screen[V[vx]+uint8(j)][V[vy]+uint8(i)] != bit {
            V[15] = 1
        } else {
            V[15] = 0
        }
        Screen[V[vx]+uint8(j)][V[vy]+uint8(i)] = bit
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.