java 将 BigDecimal/BigInteger 序列化为 ProtocolBuffers 的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1051732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:56:40  来源:igfitidea点击:

What is the best approach for serializing BigDecimal/BigInteger to ProtocolBuffers

javaprotocol-buffers

提问by Rich

I am starting to migrate a custom serialization mechanism to Protocol Buffers. One data type that will be used particularly regularly is BigDecimal.

我开始将自定义序列化机制迁移到 Protocol Buffers。将特别经常使用的一种数据类型是BigDecimal.

Does anyone know of a good way of serializing this within Protocol Buffers? Our current serialization routine uses BigDecimal.toPlainString()for serialization, and new BigDecimal(String)for deserialization - I'm assuming there's a better way.

有谁知道在 Protocol Buffers 中序列化这个的好方法吗?我们当前的序列化例程BigDecimal.toPlainString()用于序列化和new BigDecimal(String)反序列化 - 我假设有更好的方法。

My guess is to define a BigDecimalas:

我的猜测是将 a 定义BigDecimal为:

message BDecimal {
    required int32 scale = 1;
    required BInteger int_val = 2;
}

But I am not too sure how to define BigInteger- perhaps using its toByteArray()method?

但我不太确定如何定义BigInteger- 也许使用它的toByteArray()方法?

采纳答案by notnoop

Yes. You should define BigInteger as BigInteger.toByteArray() .

是的。您应该将 BigInteger 定义为 BigInteger.toByteArray() 。

My guess is that BigDecimal would be:

我的猜测是 BigDecimal 将是:


message BDecimal {
  required int32 scale = 1;
  required BInteger int_val = 2;
}

while BigInteger may be defined as

而 BigInteger 可以定义为


message BInteger {
  required bytes value = 1;
}

The code to handle BigInteger would be:

处理 BigInteger 的代码是:


  BInteger write(BigInteger val) {
    BInteger.Builder builder = BInteger.newBuilder();
    ByteString bytes = ByteString.copyFrom(val.toByteArray());
    builder.setValue(bytes);
    return builder.build();
  }

  BigInteger read(BInteger message) {
    ByteString bytes = message.getValue();
    return new BigInteger(bytes.toByteArray());
  }

回答by squiddle

Why do you want to change it? Just because you can or is there a real need (like a profiling session confirming, that serialization/deserialization takes most of the time).

你为什么要改变它?仅仅因为您可以或是否确实需要(例如确认分析会话,序列化/反序列化需要大部分时间)。

I would use a string, just because it is built in :)

我会使用一个字符串,只是因为它是内置的:)

The proposed byte array approach (What is the best approach for serializing BigDecimal/BigInteger to ProtocolBuffers) seems fine to me, if string representation seems to be an issue.

如果字符串表示似乎是一个问题,那么建议的字节数组方法(将 BigDecimal/BigInteger 序列化为 ProtocolBuffers 的最佳方法是什么)对我来说似乎很好。