长到十六进制字符串字符数
Long to hex String number of characters
你好我正在尝试构建一个随机的 16 个字符的十六进制,为此我尝试了一个 Long.toHexString(new Random().nextLong()
我的假设是它总是 return 一个 16 个字符的字符串,我说得对吗? (一旦它 returned 15 个字符)
参考 Javadoc of the method in question 应该是您的第一个停靠港:
This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s
所以不,它不会总是 16 个字符。
但是,您可以打印 16 个字符的大写十六进制字符串,前导零,使用:
String.format("%016X", longValue)
查看 toHexString(long i)
的 javadoc(强调我的)。
public static String toHexString(long i)
Returns a string
representation of the long argument as an unsigned integer in base 16.
The unsigned long value is the argument plus 264 if the argument is
negative; otherwise, it is equal to the argument. This value is
converted to a string of ASCII digits in hexadecimal (base 16) with no
extra leading 0s. If the unsigned magnitude is zero, it is represented
by a single zero character '0' ('\u0030'); otherwise, the first
character of the representation of the unsigned magnitude will not be
the zero character.
事实证明,它不会总是 16 个字符长。但是,如果你愿意,你可以用零填充:
import java.util.Random;
class Main {
public static void main(String[] args) {
String hex16Chars = String.format("%016X", new Random().nextLong());
System.out.println(hex16Chars + ", len: " + hex16Chars.length());
}
}
您会看到长度始终如预期的那样为 16。
事实证明,偷看文档确实有帮助! :)
你好我正在尝试构建一个随机的 16 个字符的十六进制,为此我尝试了一个 Long.toHexString(new Random().nextLong()
我的假设是它总是 return 一个 16 个字符的字符串,我说得对吗? (一旦它 returned 15 个字符)
参考 Javadoc of the method in question 应该是您的第一个停靠港:
This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s
所以不,它不会总是 16 个字符。
但是,您可以打印 16 个字符的大写十六进制字符串,前导零,使用:
String.format("%016X", longValue)
查看 toHexString(long i)
的 javadoc(强调我的)。
public static String toHexString(long i)
Returns a string representation of the long argument as an unsigned integer in base 16.
The unsigned long value is the argument plus 264 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s. If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character.
事实证明,它不会总是 16 个字符长。但是,如果你愿意,你可以用零填充:
import java.util.Random;
class Main {
public static void main(String[] args) {
String hex16Chars = String.format("%016X", new Random().nextLong());
System.out.println(hex16Chars + ", len: " + hex16Chars.length());
}
}
您会看到长度始终如预期的那样为 16。
事实证明,偷看文档确实有帮助! :)