Hi! Exist a component, or any other way to convert a decimal to a binary or hexadecimal?
Nope, hexadecimal (provided your number is an integer, otherwise it gets really hairy) is pretty easy with a little bit of C#, I don’t think there’s a good binary formatter in .NET, but I might be wrong.
Ok! Thanks David one more time!
@osvalijr for binary of an integer you could download the cPython component and convert using numpy:
import numpy as np
assert np.binary_repr(3) == '11'
assert np.binary_repr(10) == '1010'
And I think this would work using the native ironpython that comes Grasshopper:
I just wrote this up, so could be buggy! I feel like with the use of tolerances we could get it to work with non-integers…
import math
def is_zero(x):
return abs(x) < 1e-10
def make_bin(x,val=0):
if is_zero(x): # base case
return val
z = math.log(x,2)
val += int(math.pow(10, int(z)))
if is_zero(int(z) - float(z)): # base 2
return val
else: # recurse until base 2 or zero
rest = x - math.pow(2, int(z))
if is_zero(rest%2 - 0.0):
return make_bin(rest, val)
else:
return make_bin(rest-1, val) + 1
# Tests
assert make_bin(0) == 0
assert make_bin(1) == 1
assert make_bin(2) == 10
assert make_bin(18) == 10010
assert make_bin(32) == 100000
(Iron)Python has hex()
and bin()
that might (they only work on integers) work for you:
181005_BinHex_GHPython.gh (2.9 KB)
2 Likes