[GIS] Convert a number in attribute table to binary

arcgis-desktopfield-calculator

I would like to convert whole integers from decimal to binary in ArcGIS using the field calculator.

I am looking for the equivalent of DEC2BIN excel command.

All values are 255 or below so 8 bit is fine.

It must have 0 padding to the left. So for example 4 must be 00000100.

I can do it by exporting the attribute table to Excel and using the Dec2Bin command in Excel and rejoin the data but I would like it in a model so want to use the field calculator.

Dec2Bin (Value, 8) works in Excel.

Attached is how I would like it to look when complete.

enter image description here

So basically change the value to and 8 digit binary value stored as a text field with leading 0s so all field have 8 values.

I found this code in arcscripts but cannot get it to function.

Dim valI as integer
Dim valB as string
Dim x as integer
valI = [fieldName]
for x = 7 to 0 step -1
if valI >= 2^x then
valB = valB & 1
valI = valI – 2^x
else
valB = valB & 0
end if
Next
valB = valB & "00000000"

fieldName =
valB

Best Answer

There are many threads on this issue, here are some examples

>>> bin(100)
'0b1100100'
>>> bin(4)
'0b100'
>>> getBin = lambda x, n: x >= 0 and str(bin(x))[2:].zfill(n) or "-" + str(bin(x))[3:].zfill
>>> getBin(4,8)
'00000100'