Binary To Decimal

I got binary “1101010”. How can I change “1101010” To Number 106

I believe you can use parseInt.

@val external parseInt: (string, int) => int = "parseInt"

let i = parseInt("1101010", 2)

Js.log(i)

However this can return NaN for invalid inputs, so it might be something extra for you to take care of.

1 Like

thx. I didn’t know how to use @val external
ps. Of course, I knew parseInt :smiley:

1 Like

Using parseInt to create an int value is unsafe, because JavaScript numbers can be much bigger than the ReScript int type expects. This won’t fail when it’s parsed but it can cause unexpected issues when the value is used. Parsed numbers need to be float (and then Float.toInt can be used to constrain the result to an int).

There is a built-in external binding for this, Js.Float.fromString:

1 Like