gpt4 book ai didi

java - 长到十六进制字符串字符数

转载 作者:行者123 更新时间:2023-12-05 08:15:37 26 4
gpt4 key购买 nike

你好我正在尝试构建一个随机的 16 个字符的十六进制,为此我尝试了一个 Long.toHexString(new Random().nextLong() 我的假设是它总是返回一个 16字符字符串,我说得对吗?(一旦返回 15 个字符)

最佳答案

查看 toHexString(long i) 的 javadocs (强调我的)。

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。

事实证明,偷看文档确实有帮助! :)

关于java - 长到十六进制字符串字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com