Java:签名长到无符号长字符串 [英] Java: signed long to unsigned long string

查看:246
本文介绍了Java:签名长到无符号长字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单快捷的方法将Java签名长转换为无符号长字符串?

Is there an easy and fast way to convert a Java signed long to an unsigned long string?

-1                    ->  "18446744073709551615"
-9223372036854775808  ->  "09223372036854775808"
 9223372036854775807  ->  "09223372036854775807"
 0                    ->  "00000000000000000000"


推荐答案

以下是使用BigInteger的解决方案:

Here is a solution using BigInteger:

/** the constant 2^64 */
private static final BigInteger TWO_64 = BigInteger.ONE.shiftLeft(64);

public String asUnsignedDecimalString(long l) {
   BigInteger b = BigInteger.valueOf(l);
   if(b.signum() < 0) {
      b = b.add(TWO_64);
   }
   return b.toString();
}

这是因为两个s中(带符号)的无符号值补码只比签名值大2 (位数),而Java的 long 有64位。

This works since the unsigned value of a (signed) number in two-s complement is just 2(number of bits) more than the signed value, and Java's long has 64 bits.

BigInteger有这个很好的 toString()方法,我们可以在这里使用。

And BigInteger has this nice toString() method which we can use here.

这篇关于Java:签名长到无符号长字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆