How to Print Hexadecimal Numbers in PHP or Java

33,491

Solution 1

You need to print the numbers 1 to 30 in hexadecimal notation. Try this method for each line:

dechex ( int $number )

Solution 2

For 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.

Solution 3

    for ( int i=1 ; i <= x; i++ ) {
        System.out.printf("%02x\n", i);
    }

Solution 4

This will print hexadecimal 01-24 (with 0 padding in front of numbers less than 10)

for ($i = 1; $i <= 36; $i++) {
    printf("%02x\n", $i);
}

Solution 5

<?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
Share:
33,491
Splendid
Author by

Splendid

Updated on July 09, 2022

Comments

  • Splendid
    Splendid almost 2 years

    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.

    So take a look at this for example. We have x of files in folder. For this example x=36. X is always known.

    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.

    If possible, I would prefer PHP or Java code but I will be very grateful for any kind of help.

  • Carson Myers
    Carson Myers almost 15 years
    so simple... while($number++ < $X){ echo dechex($number)."\n"; }
  • jimyi
    jimyi almost 15 years
    What is this? Java doesn't have printf.
  • Bill the Lizard
    Bill the Lizard almost 15 years
  • Splendid
    Splendid almost 15 years
    Ah, stupid me, I wasn't thinking about hex at all... My brain ain't working at this hot days, but it's obvious that I am a real nOOb sometimes :D
  • Jared Lindsey
    Jared Lindsey almost 10 years
    Even slightly shorter: System.out.format("%x\n", number);