spacetyper
spacetyper

Reputation: 1601

Convert binary to decimal in Julia

I'd like to convert binary to decimal in Julia. It looks like parseint() became deprecated.

Is the below method the best way to do this?

julia> parse(Int,"111",2)
7

Upvotes: 7

Views: 6006

Answers (2)

Steven Siew
Steven Siew

Reputation: 873

julia> convertbinarystring2decimal(s) = parse(Int64,"0b" * s)
convertbinarystring2decimal (generic function with 1 method)

julia> convertbinarystring2decimal("110")
6

Upvotes: 0

mbauman
mbauman

Reputation: 31362

Are you starting with a string? Then yes, that's the way. If you're just wanting to write a constant in binary, then it's much easier to just use the 0b111 syntax. By default, it constructs an unsigned integer (which is displayed in hexadecimal), but you can easily convert it to a signed integer with Int(0b111).

julia> 0b110111
0x37

julia> Int(0b110111)
55

Upvotes: 12

Related Questions