0

redis-cli returns values as escaped ASCII strings, as per https://github.com/redis/redis/blob/febe102bf6d94428779f3943aea5947893301912/src/sds.c#L870-L899.

How to convert this string to corresponding bytes in Java?

Inego
  • 1,039
  • 1
  • 12
  • 19

1 Answers1

2

Here's a helper function in Kotlin (depending on Apache Commons Codec) which performs the conversion:

import org.apache.commons.codec.binary.Hex

fun decodeEscapedAscii(src: String): ByteArray {

    val list = mutableListOf<Byte>()
    var idx = 0

    while (idx < src.length) {
        val c = src[idx]
        when (c) {
            '\\' -> {
                idx++

                when (val afterSlash = src[idx]) {
                    '\\', '"' ->
                        list.add(afterSlash.toByte())
                    'n' ->
                        list.add('\n'.toByte())
                    'r' ->
                        list.add('\r'.toByte())
                    't' ->
                        list.add('\t'.toByte())
                    'a' ->
                        list.add(7)
                    'b' ->
                        list.add('\b'.toByte())

                    'x' -> {
                        idx++
                        val hex = src.substring(idx, idx + 2)
                        val decodeHex = Hex.decodeHex(hex)
                        list.add(decodeHex[0])
                        idx++
                    }
                    else -> throw IllegalStateException("Unknown char after backslash: $afterSlash")
                }
            }
            else -> {
                list.add(c.toByte())
            }
        }
        idx++
    }
    return list.toByteArray()
}
azro
  • 53,056
  • 7
  • 34
  • 70
Inego
  • 1,039
  • 1
  • 12
  • 19