0

I want to generate string dynamically according to specific input lick this if the input = 1 , the string output = 00000 and if it =10 , output = 0000a input= 16 ,output = 00010 and so on . the generated string is numbers from 0 to 9 and letters from a to f and the string length is constant for all generated strings.

and what the code if the output is not a hex , just a string like aaaaa for 1,

and aaaab for 2.

Community
  • 1
  • 1
bic096
  • 3
  • 2
  • Possible duplicate of [Convert int to hex with leading zeros](https://stackoverflow.com/questions/15919979/convert-int-to-hex-with-leading-zeros) – Lesiak Oct 26 '19 at 19:30
  • what is the logic between these values? `1` to `0000` could be minus one; `10` to `000a` just base changed; `16` to `0000f` again minus one but also base changed. Or just mistyped? – user85421 Oct 26 '19 at 19:41

2 Answers2

1

I assume you made a mistake and the output of 1 should be 00001 and the output 16 should be 00010.

Use String.format:

public static void main(String[] args) throws Exception {
    System.out.println(toHex(0, 5));
    System.out.println(toHex(1, 5));
    System.out.println(toHex(10, 5));
    System.out.println(toHex(16, 5));
}

private static String toHex(int input, int length) {
    return String.format("%0" + length + "x", input);
}

Output:

00000
00001
0000a
00010
Alex R
  • 3,139
  • 1
  • 18
  • 28
  • and same for 16? – user85421 Oct 26 '19 at 19:38
  • 1
    little hint: `%05x` would pad with zeros, no need for replace.... – user85421 Oct 26 '19 at 19:44
  • yes that was my mistake , what if the output is not a hex number , what if it just a string, what is the code for that. and than you . – bic096 Oct 26 '19 at 19:50
  • @BabikerBushra Do you mean "decimal notation" by "just a string"? If so you would have to write `"%0" + length + "d"` instead of `"%0" + length + "x"`. Take a look at the available [formatting options](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#syntax). – Alex R Oct 26 '19 at 19:56
0

Best I can see in terms of c# that fits your rules is:

string NumToHex(int num){
  if(num == 10)
    return num.ToString("x5");
  else
    return (num-1).ToString("x5");
}
Caius Jard
  • 72,509
  • 5
  • 49
  • 80