Search code examples
formatceylon

Integer to hexadecimal string


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?


Solution

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