I have a base-6 number generated by rolling a physical six-sided dice and want to convert it into base-2 / binary.
Are there built-in commands or programs that can do that for me?
If not, what is the manual way of converting the numbers?
I have a base-6 number generated by rolling a physical six-sided dice and want to convert it into base-2 / binary.
Are there built-in commands or programs that can do that for me?
If not, what is the manual way of converting the numbers?
Like Jeff hints in the comments, you can use bc
for base conversion. With regard to physical dice, the digits are usually 1 to 6, while bc
(and maths) will need digits 0 to 5, so you need to do something about that, either manually, or with something like tr
.
For example, this function would map 111
-> 0, 112
-> 1, 121
-> 6 etc.:
f() {
echo "obase=10; ibase=6; $(echo $1 | tr 1-6 0-5)" | bc;
}
The output is in decimal, you can change that by changing the value of obase
above. Or you can use the decimal number for other arithmetic.
Set total to 0
Repeat until no more roles:
multiply total by 6 #this has no effect the first time around the loop
role dice
add (number on dice -1) to total
See other answers and comments
There are a couple of POSIX tools to convert from base 6 to base 2.
However, the symbols in a dice are 1 2 3 4 5 6
while a base-6 integer should use only the symbols 0 1 2 3 4 5
, there is a difference of 1. Any tool used must take that into account. For a single digit, that is not a big issue:
The simplest is bc (or dc). The conversion of a single digit could be done as:
digit=5; echo "n=$digit - 1; obase=2; n" | bc
But for several rolls in one string, like 31256
it needs to be input as a decimal number and subtract 1 from each digit (11111
in this case) and then re-input as a base-6 number.
$ echo "ibase=6; obase=2; $(echo "31256-11111" | bc)" | bc
101001100001
Or, as text, you can convert every 6 to 5, every 5 to 4, etc.:
$ echo "ibase=6; obase=2; $(echo "31256" | tr 123456 012345)" | bc
101001100001
Another option is awk:
awk -v n=31256 '
function roll2dec(str, ret, i, c){
for (i = 1; i <= length(str); i++) {
c = substr(str, i, 1)
ret = ret * 6 + index("23456", c)
}
return ret
}
function dec2bin(dec, bin){
while (dec>0){
bin = dec%2 bin;
dec=int(dec/2)
};
return bin
}
BEGIN{
print dec2bin(roll2dec(n))
}'
101001100001