Search code examples
crystal-lang

How to you convert an Int32 into a string (base 16) with a leading 0x?


On the shell, I convert and format a number (eg 29360134) into a string, "0x1c00006":

printf "%#08x" 29360134 # -> 0x1c00006

But, in Crystal I get a different result using the same format string:

puts("%#08x" % 29360134).inspect # -> 01c00006

What's the correct way to convert an Int32 into a string with a leading 0x?


Solution

  • Crystal is currently not implementing the # flag. You have to add the prefix on your own like so:

    puts "0x%08x" % 29360134
    

    You can view the current implementation at https://github.com/crystal-lang/crystal/blob/1cd278d346b16b9ab42a62a4746086c58a8da2f9/src/string/formatter.cr#L222

    Note how there's no code path for flags.sharp.