Home > Back-end >  how to convert string value to hex
how to convert string value to hex

Time:05-05

I need to generate one combination at a time, ie I have a variable of array length and the number to which the combinations will be generated.

For example, an array of length 3 and number 11, ie the following sequences should be generated:

001
002
003
004

and so on until 101010, my code does so, but the problem is that I don't know how to convert numbers over 9 to hex

void generatePermutations(int[] intervals, int pos, String lastPerm) {
    if (pos == intervals.length)
        return;

    for (int i = 0; i <= intervals[pos]; i  ) {
        if (pos == intervals.length - 1) {
            if ((lastPerm   i).equals(String.format("%0"   intervals.length   "d", 0))) continue;
            System.out.println(lastPerm   i);
        }
        generatePermutations(intervals, pos   1, lastPerm   i);
    }
}

CodePudding user response:

You can use

String.format("%X", i)

to convert from int to a hex string "%x" for lowercase.

Applied to your code, results in:

void generatePermutations(int[] intervals, int pos, String lastPerm) {
        if (pos == intervals.length)
            return;

        for (int i = 0; i <= intervals[pos]; i  ) {
            if (pos == intervals.length - 1) {
                if ((lastPerm   String.format("%X", i)).equals(String.format("%0"   intervals.length   "d", 0))) continue;
                System.out.println(lastPerm   String.format("%X", i));
            }
            generatePermutations(intervals, pos   1, lastPerm   String.format("%X", i));
        }
    }
  • Related