简体   繁体   English

BigDecimal编码的最佳比例

[英]BigDecimal optimal scale for encoding

I need to encode a BigDecimal compactly into a ByteBuffer to replace my current (rubbish) encoding scheme (writing the BigDecimal as a UTF-8 encoded String prefixed with a byte denoting the String length). 我需要将BigDecimal紧凑地编码到ByteBuffer以替换我当前的(垃圾)编码方案(将BigDecimal写为UTF-8编码的String前缀为表示String长度的字节)。

Given that a BigDecimal is effectively an integer value (in the mathematical sense) and an associated scale I am planning to write the scale as a single byte followed by a VLQ encoded integer. 鉴于BigDecimal实际上是一个整数值(在数学意义上)和相关的标度,我计划将标度写为单个字节,后跟VLQ编码的整数。 This should adequately cover the range of expected values (ie max scale 127). 这应该足以涵盖预期值的范围(即最大标度127)。

My question: When encountering large values such as 10,000,000,000 it is clearly optimal to encode this as the value: 1 with a scale of -10 rather than encoding the integer 10,000,000,000 with a scale of 0 (which will occupy more bytes). 我的问题:当遇到诸如10,000,000,000这样的大值时,将其编码为值为1显然是最佳的:1为-10,而不是编码整数10,000,000,000,其标度为0(这将占用更多字节)。 How can I determine the optimal scale for a given BigDecimal ? 如何确定给定BigDecimal的最佳比例? ... In other words, how I can determine the minimum possible scale I set assign a BigDecimal without having to perform any rounding? ...换句话说,我如何确定我设置的最小可能比例分配BigDecimal而不必执行任何舍入?

Please do not reference the term "premature optimisation" in your answers :-) 请不要在答案中引用“过早优化”一词:-)

BigDecimal#stripTrailingZeros似乎正在这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM