Java convert bytes to binary safe string

梦想与她 提交于 2019-12-12 11:51:35

问题


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 works for me, but it makes data larger, any better idea?

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.

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


回答1:


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

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




回答2:


The only safe way to serialize a binary object (such as a protobuf object) is to base64 encode it. Base64 has a 33% overhead but gives you the ability to safely convert from arbitrary binary data to text (such as for use in an xml file) and back.



来源:https://stackoverflow.com/questions/13857824/java-convert-bytes-to-binary-safe-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!