BigDecimal 编码的最佳尺度
我需要将 BigDecimal
紧凑地编码为 ByteBuffer
以替换我当前的(垃圾)编码方案(将 BigDecimal
编写为 UTF-8 编码) String
前缀为表示 String
长度的字节。
鉴于 BigDecimal
实际上是一个整数值(在数学意义上)和关联的比例,我计划将比例编写为单个字节,后跟 VLQ 编码 整数。这应该充分覆盖预期值的范围(即最大比例 127)。
我的问题:当遇到诸如 10,000,000,000 这样的大值时,显然最好将其编码为值:1,比例为 -10,而不是使用比例 0 编码整数 10,000,000,000 (这将占用更多字节)。如何确定给定 BigDecimal
的最佳标度? ...换句话说,我如何确定我设置的最小可能比例分配一个 BigDecimal
而无需执行任何舍入?
请不要在您的答案中引用“过早优化”一词:-)
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).
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. This should adequately cover the range of expected values (i.e. max scale 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). How can I determine the optimal scale for a given BigDecimal
? ... In other words, how I can determine the minimum possible scale I set assign a BigDecimal
without having to perform any rounding?
Please do not reference the term "premature optimisation" in your answers :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
BigDecimal#stripTrailingZeros似乎正在做这个。
BigDecimal#stripTrailingZeros seems to be doing this.