douhezhan5348 2015-03-11 21:21
浏览 453
已采纳

golang:对非常长的二进制位字符串表示形式的按位运算

As an exercise, in input I got 2 very big string containing long binary representation here a short one but could have more than 100 bits:

Example

11100
00011

With output in bitwise OR (as string)

11111

My approach was to parse each string characters and make a bitwise OR and build a new string but it is too long to process on big entry and not effective.

Then ParseInt method is restricted to a 64 bit length

num1, err:= strconv.ParseInt("11100", 2, 64)
num2, err:= strconv.ParseInt("00011", 2, 64)
res := num1 | num2

How to deal with a bitwise OR between 2 string binary representation?

  • 写回答

3条回答 默认 最新

  • dppxp79175 2015-03-11 21:31
    关注

    You could create the resulting bitwise OR string by doing character comparisons, or you can perform arbitrary large numeric operations using math/big. Here is an example of such an operation:

    package main
    
    import "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()
    }
    

    Go Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备