NumToHex.cs

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
					
public class Program
{
	public static readonly char[] HEX_SYMBOLS = new char[] 
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
             'a', 'b', 'c', 'd', 'e', 'f'};
        
    public static string NumToHex(int num) {
        if (num == 0)
            return "0";
        
        var rest = (uint)num;
        var res = new List<char>();
        while (rest > 0)
        {
            var digit = rest % 16;
            rest /= 16;
            res.Add(HEX_SYMBOLS[digit]);
        }
        
        res.Reverse();
        return string.Join("", res);
    }
	
	public static void Main()
	{
		Console.WriteLine("UniLecs");
		
		// tests
		Console.WriteLine(NumToHex(26)); // 1A
		Console.WriteLine(NumToHex(-1)); // ffffffff
	}
}
;