Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
part 21 encode/decode binary
//my version of http://groovyconsole.appspot.com/script/646001
def in_bin = ["0", "1", "111011", "100100101010", "001101", "01000" ]
def p21_rep = [] //in_bin encoded in part 21 format
def d = [] //extra binary digits in p21_rep
def hex = [] //hex part of p21_rep
def nibbles = [] //number of hex digits
def out_bin = [] //p21_rep decoded
def num_bits = [] //number of used bits
def zeros = [] //number of binary zeros to prepend to out_bin
def padded = [] //num_bits + d
//encode
in_bin.each { value ->
def i = Integer.parseInt(value, 2)
def rem = (4 - i.toString().size()%4)%4
def nibble = Integer.toHexString(i)
def pad = value.length() - (nibble.length()*4)
if( pad < 0 ) {
pad = 0
}
zeros << pad
p21_rep << (rem + "0" * Math.ceil(pad/2) + nibble).toUpperCase()
}
//decode
p21_rep.eachWithIndex() { value, i ->
d << value[0]
def h = value.substring(1)
hex << h
def bs = Integer.toBinaryString(Integer.parseInt(h,16))
out_bin << "0" * zeros[i] + bs
def n = bs.length() + zeros[i]
num_bits << n
def bits = n + Integer.parseInt(value[0])
padded << bits
nibbles << bits / 4
}
printf("in: %s\nout: %s\np21: %s\nextra bits: %s hex: %s\n", in_bin, out_bin, p21_rep, d, hex)
printf("used bits: %s extra+used bits: %s\nout_bin pad: %s # nibbles: %s", num_bits, padded, zeros, nibbles)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment