At the bottom you can find a simpler way.
Binary
Binary to decimal
| (1) binary → decimal
|
s = "01111001"
print(int(s, 2)) # 121
|
import std/strutils
let s = "01111001"
echo fromBin[int](s) # 121
|
fromBin() (see the docs) is a generic function. The type parameter "[int]" means the return type of the function. That is, after the conversion we want an int as a result. You could also specify int8, uint8, etc.
Decimal to binary
| (2) decimal → binary
|
print(bin(121)) # 0b1111001
|
import std/strutils
echo toBin(121, 8) # 01111001
echo toBin(121, 4) # 1001 ; truncated to length 4
echo toBin(121, 16) # 0000000001111001
let s = toBin(121, 16)
echo insertSep(s, digits=4) # 0000_0000_0111_1001
echo insertSep(s, digits=8) # 00000000_01111001
|
func toBin(x: BiggestInt; len: Positive): string {. ... .}
The len parameter must be provided, and the resulting string will be that long.
However! What if I don't know the length of the binary representation in advance? If len is not long enough, the resulting string will be truncated. A possible solution is to set len long enough and then remove the leading 0s:
echo toBin(121, 64).lstrip("0") # 1111001
You can find lstrip() here.
Hexa
Decimal to hexa
| (1) decimal → hexa
|
|
|
import std/strutils # strip, split, join
echo toHex(49) # 0000000000000031
echo toHex(49, 4) # 0031 ; truncated to length 4
echo toHex(49).lstrip("0") # 31
|
lstrip() is here.
Hexa to decimal
| (2) hexa → decimal
|
#!/usr/bin/env python3
print(int("0x0801", 16)) # 2049
print(int("0801", 16)) # 2049
|
#!/usr/bin/env nimbang
#off:nimbang-args c -d:release
#nimbang-settings hideDebugInfo
import std/strutils # strip, split, join
echo fromHex[int]("0x0801") # 2049
echo fromHex[int]("0801") # 2049
|
See the docs here.
The simple way
import std/strformat # &"Hello {name}!"
let
n = 121
bin = &"{n:b}"
hex = &"{n:x}"
echo bin # 1111001
echo hex # 79
Here, there's no need to specify an upper bound for the length of the resulting strings.