Author Archives: Lamonte

Crystal Lang – Converting Decimal to Hex

I’ve been writing crystal again and started working on a new api adaption in crystal. One thing I’ve noticed is there’s no actual library to check details about images currently, so I started to play around and figure out how I could do this in pure crystal. I’m not the brightest tool in the shed, but I’m good at using my resource skills to solve a problem.

First off, I needed to figure out how to check if an image is a valid type being submitted to the api that I’m writing for my api adaption. So I knew I needed to deal with the raw bytecode directly, but I didn’t know how I’d actually use it. So after a few minutes of googling I found out I could use common file signatures to figure out if an image is a certain image type based on HEX data. Now there’s this site that documented a list of common file signatures and so I went from there.

I was trying to figure out how to convert a decimal from the byte[] array to the hex data I needed and I couldn’t figure out how to do it using crystal’s standard library directly. So I did what any programmer would do and opened up stackoverflow. I found an example written in python and I used that example and converted it into crystal code.

And everything worked out. So I’m like cool, this is perfect, now I can use that signature data and compare hex values to check for valid image types as a base. So I post on the gitter.im channel (dev’s talk about and answer questions regarding crystal) asking if something similar to this would be added to the stdlib and one of the users (not sure if he’s a main dev) hit me with the ‘oh you can do this’ and gave me this example:

decimal.to_s(16)

I’m like, seriously? I literally cut my 10 line python adaption to 1 line. This isn’t even documented or it isn’t documented well, so how would I have known about this feature. So now I’m writing a blog on how easy it is to convert a decimal to hex value using crystal. Man I love this language.