如何 encode/decode protocol buffer binary data(Integer) to string and string to binary?

How to encode/decode protocol buffer binary data(Integer) to string and string to binary?

我正在使用 Protocol buffersmack.

制作程序

smack (xmpp) 只能传输字符串类型的数据。而protocol buffer可以产生字节数组数据。 所以,我这样做

  1. 使用协议缓冲区制作字节[]数据。
  2. 使用 base64
  3. 将 byte[] 数据编码为字符串
  4. 使用 smack 传输
  5. 将接收到的字符串(使用 base64 编码)解码为字符串
  6. 将解码后的字符串更改为字节[]
  7. 使用协议缓冲区从 byte[] 解析数据。

那么每个值都是完美的,没有 Integer 类型值。 Integer 的值已更改。 这些值在 xxxx.proto

例如转换string abc = "hello" int age = 13300string abc = "hello" int age = 217014255

仅更改了 int

有什么问题?

  1. decode received string(encoded using base64) to string
  2. change decoded string to byte[]

由于您没有提供代码,所以很难确定,但我怀疑这些步骤看起来像这样:

String encoded = readMessage();
String decoded = new String(base64Decode(encoded), "ASCII");
byte[] bytes = decoded.getBytes("UTF-8");

这是错误的,因为您实际上在这里所做的是将解码后的字节解释为 ASCII 字符串,然后将它们转换回使用 UTF-8 编码的字节。我相信这会导致您所描述的损坏:如果您查看字节模式,您会看到原始消息恰好有一个字节设置了最高位(使其 ASCII 无效),并且在损坏的消息中字节已替换为 Unicode 替换字符的 UTF-8 编码(用于标记错误)。您的字符串数据没有损坏,因为它只包含 ASCII,并且 Protobuf 元数据没有损坏,因为您的字段编号的 none 大于 15,因此标签都是 1 个字节,没有设置高位(这使得它们有效的 ASCII)。

无论如何,String class 不能包含原始字节。它只能包含 Unicode 文本。因此,将 base64Decode() 的输出表示为 String 是错误的。它只能是 byte[]。也就是说,它应该看起来像:

String encoded = readMessage();
byte[] decoded = base64Decode(encoded);