2

I need to do bitwise OR of two binary strings.

For example, if the binary strings are "110001" and "101101", then I need the result as "111101".

How can I do this in Swift ?

1 Answer 1

7

You can convert it first into Int

let a = Int("110001", radix: 2)!
let b = Int("101101", radix: 2)!
let c = a | b

let stringResult = String(c, radix: 2, uppercase: false)

More info:

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for the answer. Can you tell me how can I do this for very big binary string. For example a binary string like this : "1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010". Current solution can't convert this number which is pretty long.
you will want to iterate over the characters in both of your input strings and if either character is "1" then you would write "1" to the output string, otherwise you would write "0". Iterating both strings at the same time can be achieved with zip assuming both input strings are the same length.
@SalehMasum That string is 100 char long, what would it represent? Maybe you should divide it into smaller chunks first before converting it.
@theoriginalbit yes it is achievable by a for loop but the problem is it takes too long that's why I am looking for alternatives. A BigInteger class can do this job but swift does not have it.
@SalehMasum when you say "takes too long" what exactly is your definition of "too long". I was able to just perform a measure with a 500 char long string and it took an average of 0.005 seconds.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.