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?

1 Answer 1

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()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.