Created
August 21, 2021 09:47
-
-
Save hastebrot/5c446af4301cedc01a7ffe62f8f105d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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