Java将字节转换为二进制安全字符串 [英] Java convert bytes to binary safe string

查看:361
本文介绍了Java将字节转换为二进制安全字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些以字节为单位的数据,我想将它们放入Redis,但是Redis仅接受二进制安全字符串,并且我的数据具有一些二进制非安全字节.那么如何将这些字节转换为二进制安全字符串,以便可以将它们保存到Redis?

I have some data in bytes, and I want to put them into Redis, but Redis only accepts binary safe string, and my data has some binary non-safe bytes. So how can I convert these bytes into binary safe string so that I can save them to Redis?

Base64对我有用,但是它使数据更大,还有更好的主意吗?

Base64 works for me, but it makes data larger, any better idea?

更新:我想将protobuf对象序列化为Redis,并且序列化的数据为'\ x00',所以当我从Redis读取数据时,无法将数据反序列化为对象.然后我尝试了base64,它可以正常工作,但是尺寸更大.

UPDATE: I want to serialize my protobuf object to Redis, and the serialized data has '\x00', so when I read the data from Redis, I can not deserialize the data to object. Then I tried base64, it works fine, but with larger size.

所以我想弄清楚如何安全地以较小的大小将二进制数据(protobuf对象)序列化到Redis

So I want to figure out how to serialize binary data (protobuf object) to Redis safely and with smaller size

推荐答案

您可以尝试ISO-8859-1编码.这在字节和字符之间使用了一对一的映射.

You could try ISO-8859-1 encoding. This uses a one to one mapping between bytes and chars.

这仍然可能导致损坏,具体取决于Redis为什么需要此二进制安全"字符串.您可能必须使用base64.

This could still result in corruption depending on why Redis need this "binary safe" string. You may have to use base64.

这篇关于Java将字节转换为二进制安全字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆