1

I know how to write hexadecimal literal integers (#A3) in Ceylon. I also know how to parse hexadecimal integers in Ceylon.

Integer? integer = parseInteger("A3", 16);
print(integer.string); // 163

How do I go the other way, get the hexadecimal string representation of an integer?

drhagen
  • 8,331
  • 8
  • 53
  • 82
  • Interestingly, I also had to figure this out when answering [your recent question about crypto functions](https://stackoverflow.com/q/49717005/600500) :-) – Paŭlo Ebermann Apr 08 '18 at 17:33
  • By the way, you can omit the `.string` when using `print(...)` ... it accepts an Object, and will apply `.string` on it anyways. – Paŭlo Ebermann Apr 08 '18 at 17:34

2 Answers2

2

Use the Integer.parse and Integer.format functions. They both take a radix, which can be used to generate the string of an integer using an arbitrary base (16 for hexadecimal). By default formatInteger generates the string with lowercase letters. Use the uppercased property on the string if you want the uppercase version.

Integer|ParseException integer = Integer.parse("A3", 16);
assert(is Integer integer);
print(Integer.format(integer, 16)); // a3
print(Integer.format(integer, 16).uppercased); // A3

Note that format is not an instance method of Integer; it is a static method, so you can't do integer.format(16).

Also, note that parse returns a ParseException on failure rather than Null so that there is more information in that failing case.

drhagen
  • 8,331
  • 8
  • 53
  • 82
0

Edit: Both the parseInteger and formatInteger functions are deprecated since static methods were added, use the Integer.format function instead.

Use the formatInteger function.

Integer? integer = parseInteger("A3", 16);
assert(exists integer);
print(formatInteger(integer, 16)); // a3
drhagen
  • 8,331
  • 8
  • 53
  • 82
  • Why do you have two answers saying basically the same? Could you delete one and incorporate the content into the other? – Paŭlo Ebermann Apr 08 '18 at 17:32
  • @PaŭloEbermann They seem like different answers to me. One is "use top-level `formatInteger`", the other is "use static method `Integer.format`. I'll edit them to remove any redundant information. – drhagen Apr 08 '18 at 17:56