Skip to content

Instantly share code, notes, and snippets.

@hastebrot
Created August 21, 2021 09:47
Show Gist options
  • Save hastebrot/5c446af4301cedc01a7ffe62f8f105d8 to your computer and use it in GitHub Desktop.
Save hastebrot/5c446af4301cedc01a7ffe62f8f105d8 to your computer and use it in GitHub Desktop.
// https://stackoverflow.com/questions/7487917/convert-byte-array-to-escaped-string
fun encodeToEscapedString(bytes: ByteArray): String {
// 0x00..0x1f = non-printing characters
// 0x20 = SPACE
// 0x21..0x7e = printing characters
// 0x7f = DELETE
val string = StringBuilder()
val intSize = 0xff
val byteRange = 0x20..0x7e
for (byte in bytes) {
val intByte = byte.toInt()
when (byte) {
in byteRange -> string.append(intByte.toChar())
else -> string.append(String.format("\\0x%02x", (intByte and intSize).toByte()))
}
}
return string.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment