猿问

golang:对很长的二进制位串表示进行按位运算

作为练习,在输入中,我得到了 2 个非常大的字符串,其中包含长二进制表示,这里是一个短字符串,但可能超过 100 位:


例子


11100

00011

按位或输出(作为字符串)


11111

我的方法是解析每个字符串字符并进行按位或运算并构建一个新字符串,但是在大条目上处理时间太长并且无效。


然后 ParseInt 方法被限制为 64 位长度


num1, err:= strconv.ParseInt("11100", 2, 64)

num2, err:= strconv.ParseInt("00011", 2, 64)

res := num1 | num2

如何处理 2 个字符串二进制表示之间的按位或?


青春有我
浏览 328回答 3
3回答

紫衣仙女

您可以通过进行字符比较来创建结果按位 OR 字符串,或者您可以使用math/big. 以下是此类操作的示例:package mainimport "fmt"import "math/big"func main() {    num1 := "11100"    num2 := "00011"    var bigNum1 big.Int    var bigNum2 big.Int    var result big.Int    if _, ok := bigNum1.SetString(num1, 2); !ok {        panic("invalid num1")    }    if _, ok := bigNum2.SetString(num2, 2); !ok {        panic("invalid num2")    }    result.Or(&bigNum1, &bigNum2)    for i := result.BitLen() - 1; i >= 0; i-- {        fmt.Print(result.Bit(i))    }    fmt.Println()}

元芳怎么了

这个怎么样:package mainimport "fmt"func main(){&nbsp; &nbsp; a :=&nbsp; &nbsp;"01111100"&nbsp; &nbsp; b := "1001000110"&nbsp; &nbsp; var longest, len_diff int&nbsp;&nbsp; &nbsp; if len(a) > len(b) {&nbsp; &nbsp; &nbsp; &nbsp; longest = len(a)&nbsp; &nbsp; &nbsp; &nbsp; len_diff = len(a) - len(b)&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; longest = len(b)&nbsp; &nbsp; &nbsp; &nbsp; len_diff = len(b) - len(a)&nbsp; &nbsp; }&nbsp; &nbsp; temp_slice := make([] byte, longest)&nbsp; &nbsp; var a_start, b_start int&nbsp; &nbsp; if len(a) > len(b) {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < len_diff; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp_slice[i] = a[i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; a_start = len_diff&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < len_diff; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp_slice[i] = b[i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; b_start = len_diff&nbsp; &nbsp; }&nbsp; &nbsp; for i := 0; i < (longest - len_diff); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if a[a_start + i] == '1' ||&nbsp; b[b_start + i] == '1' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp_slice[len_diff + i] = '1'&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp_slice[len_diff + i] = '0'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(string(temp_slice))}
随时随地看视频慕课网APP

相关分类

Go
我要回答