Friday, January 29, 2021

Convert Decimal Number to Hexadecimal

Problem: Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Example:

Input:
18

Output:
"12"3
Input:
-2

Output:
"fffffffe"


Approach: Basically we will convert every 4 bits to appropriate hexadecimal digit. We can use 0xF mask to get these four bits and then we will right shift the number by 4. We will do it till the given number becomes 0.

The only problem with this approach is the negative number as while shifting right the system adds 1 to fill the left part. Because of it we can have an infinite loop. We can use a count variable to solve this problem as if you see we are right shifting by 4 bits so at max we need to right shift (32/4=) 8 times or sizeof(int) * 2 times.

That's all! 


Implementation in C#:

        public static string ToHex(int num)

        {

            if (num == 0)

            {

                return "0";

            }

            string result = string.Empty;

            int count = 0; // To handle negative numbers

            while (num != 0 && count < 8)

            {

                ++count;

                int targetNum = num & 0xf;

                result = GetHexDigit(targetNum) + result;

                num >>= 4;

            }

            return result;

        }


        private static char GetHexDigit(int num)

        {

            if (num >= 0 && num <= 9)

            {

                return (char)(num + '0');

            }

            return (char)((num - 10) + 'a');

        }


Complexity: O(num of bits)

No comments:

Post a Comment