如何在 PHP 或 Java 中打印十六进制数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1269573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Print Hexadecimal Numbers in PHP or Java
提问by Splendid
I need to print some data (a little bit strange formatted). I was writing it in PHP with if ($num%10==9) but it was impossible for me to get correct output.
我需要打印一些数据(格式有点奇怪)。我用 if ($num%10==9) 用 PHP 编写它,但我不可能获得正确的输出。
So take a look at this for example. We have x of files in folder. For this example x=36. X is always known.
所以看看这个例子。我们在文件夹中有 x 个文件。对于此示例,x=36。X 总是已知的。
Output should look like this:
输出应如下所示:
01
02
03
04
05
06
07
08
09
0a
0b
0c
0d
0e
0f
10
11
...
19
1a
...
1f
20
...
24
Sorry for the such a long "list" but I believe that you know what I need now. So, after each number which ends with 9 we have num(a,b,c,d,e,f) and then number which follows previous number with 9 on the end. (Ex. 3a...3f,40..49). And what is most important is that the number of printed lines must be equal to x.
抱歉有这么长的“列表”,但我相信你知道我现在需要什么。因此,在每个以 9 结尾的数字之后,我们有 num(a,b,c,d,e,f) ,然后是前一个数字后面的数字,最后是 9。(例 3a...3f,40..49)。最重要的是打印的行数必须等于x。
If possible, I would prefer PHP or Java code but I will be very grateful for any kind of help.
如果可能,我更喜欢 PHP 或 Java 代码,但我将非常感谢任何帮助。
采纳答案by Michael Sofaer
You need to print the numbers 1 to 30 in hexadecimal notation. Try this method for each line:
您需要以十六进制表示法打印数字 1 到 30。对每一行试试这个方法:
dechex ( int $number )
回答by jimyi
This will print hexadecimal 01-24 (with 0 padding in front of numbers less than 10)
这将打印十六进制 01-24(在小于 10 的数字前填充 0)
for ($i = 1; $i <= 36; $i++) {
printf("%02x\n", $i);
}
回答by Unknown
<?php
function blah($n) {
for($i=1;$i<=$n;$i++) {
printf("%02x\n", $i);
}
}
blah(36);
?>
01
02
03
04
05
06
07
08
09
0a
0b
0c
0d
0e
0f
10
11
12
13
14
15
16
17
18
19
1a
1b
1c
1d
1e
1f
20
21
22
23
24
回答by objects
for ( int i=1 ; i <= x; i++ ) {
System.out.printf("%02x\n", i);
}
回答by Falaina
For Java:
对于 Java:
System.out.println(Integer.toHexString(number));
or
或者
System.out.println(String.format("%x", number));
The latter has more options for formatting the hex string.
后者有更多的选项来格式化十六进制字符串。