Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang: bitwise operation on very long binary bit string representation

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?

like image 276
darul75 Avatar asked Feb 11 '23 17:02

darul75


1 Answers

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

like image 132
Tim Cooper Avatar answered Feb 14 '23 00:02

Tim Cooper