# Decimal to Hexadecimal using Bitwise, Bit Shift Operations in Java

I recently wanted to create a simple function in JavaScript which allowed me to generate a random background colour for a small experiment I was working on. The implementation I came up with worked very well, but the decimal-hexadecimal representation conversion was all wrapped up in one ‘toString(16)’ function call. I was very interested in how I could go about creating this method myself and decided on the Java language for the attempt. The discussed functionality is already present in the Java language to, within the ‘java.lang.Integer’ class as ‘toHexString’.

Hexadecimal uses the positional base system of 16, where each digit can represent four binary digits (bits). Taking a look at the documentation you will see that a Java integer is able to hold a 32bit signed, two’s complement value between -2^31 and 2^31-1. These two findings allow us to deduce that the smallest and largest integer numbers can be represented in a maximum of 8 hexadecimal positions. The discussed two’s compliment is a widely used scheme within computing, using the most significant bit to determine if the value is negative or not. To convert a negative number to and from a two’s complement representation, a simple inversion of each binary bit and addition by one needs to take place. With this knowledge we can now go about implementing the solution found below.