How can I convert a bitstring to the binary form in Julia

661 Views Asked by At

I am using bitstring to perform an xor operation on the ith bit of a string:

string = bitstring(string ⊻ 1 <<i)

However the result will be a string, so I cannot continue with other i.

So I want to know how do I convert a bitstring (of the form “000000000000000000000001001”) to (0b1001)?

Thanks

2

There are 2 best solutions below

2
On BEST ANSWER

You can use parse to create an integer from the string, and then use string (alt. bitstring)to go the other way. Examples:

julia> str = "000000000000000000000001001";

julia> x = parse(UInt, str; base=2) # parse as UInt from input in base 2
0x0000000000000009

julia> x == 0b1001
true

julia> string(x; base=2) # stringify in base 2
"1001"

julia> bitstring(x) # stringify as bits (64 bits since UInt64 is 64 bits)
"0000000000000000000000000000000000000000000000000000000000001001"
0
On

don't use bitstring. You can either do the math with a BitVector or just a UInt. No reason to bring a String into it.