Skip to content

Instantly share code, notes, and snippets.

@ptaylor
Created January 20, 2017 12:34
Show Gist options
  • Save ptaylor/93947caeadb5acb8f164e696e364829b to your computer and use it in GitHub Desktop.
Save ptaylor/93947caeadb5acb8f164e696e364829b to your computer and use it in GitHub Desktop.
Convert a byte array to a readable string with ASCII and EBCDIC characters
def bytes2String(byte[] bytes) {
long count = 0
long max = 16
def dump = '\n POS | DATA | ASCII | EBCDIC'
def curHex = ''
def curChars = ''
def curCvtChars = ''
def printable = { char c ->
char unknown = '.'
(c >= ' ' && c <= '~') ? c : unknown
}
def appendLine = { hex, chars , cvtChars ->
dump += sprintf("\n %04x |%-48s | %-16s | %-16s", count - 16, hex, chars, cvtChars)
}
def fromEbcdic = { b ->
new String([b] as byte[], 'Cp500').charAt(0)
}
bytes.each { b ->
if (count % max == 0 && count != 0) {
appendLine(curHex, curChars, curCvtChars)
curHex = ''
curChars = ''
curCvtChars = ''
}
curHex += sprintf(" %02x", b)
char c = (char) b
curChars += printable(c)
curCvtChars += printable(fromEbcdic(b))
count ++
}
if (curHex != '') {
appendLine(curHex, curChars, curCvtChars)
}
dump
}
byte[] bytes = [48,54,50,48,-126,32,0,0,-128,0,0,22,0,0,0,0,16,0,1,0,48,50,50,52,49,51,52,52,51,55,48,48,54,53,57,49,48,54,48,48,48,48,48,48,48,53,52,54,48,48,48,48,48,48,73,78,86,65,76,73,68,32,84,82,65,78,67,79,68,69,32,45,32,70,73,82,83,84,32,50,56,53,32,66,89,84,69,83,32,73,78,32,70,73,69,76,68,32,49,50,48,48,49,54,77,67,66,78,54,50,48,48,54,48,48,48,48,55,89,32,48,48,57,77,67,67,74,66,87,88,55,89,48,53,48,48,48,48,48,48,56,49,-112,-104,-112,-112,-28,22,22,-112,-112,-112,-112,-112,-104,-112,-112,-112,-112,-112,-112,-112,-112,-108,-112,-112,-112,-112,-112,-112,-112,-112,-112,-112,-112,-112,-112,-112,-111,-106,-107,-107,-107,-107,-107,-107,-107,-107,-107,-107,-107,-107,-108,-108,-108,-108,-112,22,22,-108,-112,-111,-108,-107,22,-107,-112,-112,-112,-112,-112,22,-112,-106,-112,-111,-107,-106,-111,-112,22,4,-112]
println bytes2String(bytes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment