Click here to Skip to main content
15,888,351 members
Articles / Programming Languages / C#
Article

Hexadecimal, Binary, and Decimal conversions

Rate me:
Please Sign up or sign in to vote.
4.65/5 (24 votes)
22 Apr 20052 min read 230.7K   6.9K   83   27
This project contains a class aimed to all possible combinations for hexadecimal, binary, and decimal conversions.

Sample Image - BinaryAndHexConversions.jpg

Introduction

By now, you would think that Microsoft would have a set of standard functions available to do Hexadecimal, Binary, and Decimal conversions. I looked around and found the BitArray, but it was not enough for, what I needed here is a set of classes to do all of these conversions including decimal conversions to signed integers and unsigned integers.

The Project

The project consists of a Bits class to do all the bit manipulations, a Hex class to do all the hexadecimal manipulations, a Conversion class that consists of static methods to do miscellaneous set of conversions among hexadecimal, binary, and decimal conversions. The project also includes a HexTextBox class and a HexGrid class.

The HexTextBox class is derived from RichTextBox and its purpose is to ensure that the user enters only valid digits that are within a valid range. The class can be set to Hexadecimal mode, Decimal mode, and Binary mode. When in hexadecimal mode, it prevents user from entering digits that are not hexadecimal. Same functionality for decimal and binary mode. In binary mode, the tooltip is enabled to show the bit position as the mouse is moved across the text box.

The HexGrid class is derived from DataGrid and can be used to edit hexadecimal sets of data.

Conversions Available

C#
public static string IntToBin(int number, int numBits)
public static string UIntToBin(uint number, int numBits)
public static string HexToBin(string hexData)
public static int BinToInt(string binData)
public static uint BinToUInt(string binData)
public static string BinToHex(string binData)
public static int HexToInt(string hexData)
public static uint HexToUInt(string hexData)
public static string IntToHex(int data, int numBytes)
public static string UIntToHex(uint data, int numBytes)
public static int UIntToInt(uint data, int numBits)
public static uint IntToUInt(int data, int numBits)

Additional Conversions

You can add many more conversions as needed. The constructors of the Bits and Hex classes have additional overloads that you can use to create additional conversions.

For example, to convert from an array of bytes to a bit string, you would use the following code:

C#
byte[] byteArray = new byte[] {1,2,3,4,5,6,7,8}; 
string bitString = new Bits(byteArray).ToString();

Additional Documentation

The project includes full documentation with descriptions available for all public methods. The documentation was created with NDoc.

How to Use the Code?

To use the code you just need to include the "Bin" project in your solution, add it to your references and then you should be able to start using any of the conversions available.

For example, to convert from a hexadecimal string to binary string:

C#
string hexData = "AABBCCDD01234567";
string binData = Conversion.HexToBin(hexData);

Conclusion

I hope, you find these classes useful and let me know when you find bugs so that I can correct them in my code.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to read a text file consisting of alphanumeric characters, white spaces & punctuations and then convert the data into binary values using ASCII codes, in C language Pin
Dineshbabu Uvarajulu16-Oct-14 3:26
Dineshbabu Uvarajulu16-Oct-14 3:26 
AnswerRe: How to read a text file consisting of alphanumeric characters, white spaces & punctuations and then convert the data into binary values using ASCII codes, in C language Pin
rudy.net16-Oct-14 7:40
rudy.net16-Oct-14 7:40 
QuestionIs this DLL licensed freeware? Pin
Khadar12331-Mar-09 1:31
Khadar12331-Mar-09 1:31 
AnswerRe: Is this DLL licensed freeware? Pin
rudy.net31-Mar-09 10:06
rudy.net31-Mar-09 10:06 
GeneralGenius!! Pin
indogerman12-Feb-09 23:11
indogerman12-Feb-09 23:11 
Generalunable to open file Pin
metoofaiza1-Nov-08 21:23
metoofaiza1-Nov-08 21:23 
Generalgood day!! Pin
maRk_maGic15-Jun-08 17:50
maRk_maGic15-Jun-08 17:50 
GeneralRe: good day!! Pin
rudy.net16-Jun-08 8:42
rudy.net16-Jun-08 8:42 
QuestionCAN SHOW ME the CODE HEX to DEC in JAVA Pin
ranzJR22-Nov-07 18:55
ranzJR22-Nov-07 18:55 
AnswerRe: CAN SHOW ME the CODE HEX to DEC in JAVA Pin
rudy.net26-Nov-07 1:17
rudy.net26-Nov-07 1:17 
Generaldisplay a binary file in heaxdecimal Pin
NEKSA16-Jul-06 0:13
NEKSA16-Jul-06 0:13 
GeneralRe: display a binary file in heaxdecimal Pin
rudy.net17-Jul-06 3:51
rudy.net17-Jul-06 3:51 
Generalsigned vs unsigned Pin
Talal Sultan10-May-06 3:22
Talal Sultan10-May-06 3:22 
GeneralRe: signed vs unsigned Pin
rudy.net10-May-06 18:55
rudy.net10-May-06 18:55 
QuestionConvert from Hex into Binary Pin
ranycodeproject17-Apr-06 22:05
ranycodeproject17-Apr-06 22:05 
AnswerRe: Convert from Hex into Binary Pin
rudy.net18-Apr-06 2:36
rudy.net18-Apr-06 2:36 
GeneralUpdates to this component Pin
Eric Engler6-Apr-06 5:15
Eric Engler6-Apr-06 5:15 
GeneralRe: Updates to this component Pin
rudy.net6-Apr-06 12:29
rudy.net6-Apr-06 12:29 
General.NET ver 2.0 Pin
gordsh19-Jan-06 9:29
gordsh19-Jan-06 9:29 
GeneralRe: .NET ver 2.0 Pin
rudy.net19-Jan-06 9:41
rudy.net19-Jan-06 9:41 
Generalsuggestions Pin
Eric Engler2-May-05 4:38
Eric Engler2-May-05 4:38 
GeneralMy code Pin
DrGUI29-Apr-05 11:08
DrGUI29-Apr-05 11:08 
Hi!
Your code will be faster for your defined data types, but you can have my code for general conversion up to base 36 or something.
I must have written it about 5 years ago; I was only 10 then so it's in VB6, probably inefficient and poorly written. I'm sorry if it is and you'll be glad that I've moved from VB 6 to VB .NET then to C#.
Do whatever you want with the code below

'Can convert from any base to any other base<br />
<br />
Option Explicit<br />
<br />
Private Sub cmdCalculate_Click()<br />
    Dim aInputNum() As Double<br />
    Dim aOutputNum() As Double<br />
    Dim i As Long<br />
    Dim Base10Num As Variant<br />
    <br />
    On Error GoTo defaulterr<br />
    <br />
    'Convert the input number to base 10<br />
    <br />
    'resize the array holding the numbers of the characters<br />
    ReDim aInputNum(Len(InputNum.Text))<br />
    <br />
    'put the characters into an array of characters from a string and converts other symbols<br />
    For i = 0 To Len(InputNum.Text) - 1<br />
        aInputNum(i) = ConvertIntoNum10(Mid(InputNum.Text, i + 1, 1))<br />
    Next i<br />
<br />
    On Error GoTo base10err<br />
    <br />
    'convert to base 10<br />
    For i = 0 To Len(InputNum.Text) - 1<br />
        Base10Num = Base10Num + (aInputNum(i) * (FirstBase.Text ^ (Len(InputNum.Text) - i - 1)))<br />
    Next i<br />
    <br />
    Erase aInputNum<br />
    <br />
    NumInBase10.Text = Format$(Base10Num, "########################################")<br />
    <br />
    'convert base 10 to the other base<br />
    <br />
    'find the biggest number that fits into Base10Num<br />
    Dim MaxTableSize As Long<br />
    Do<br />
        If Val(SecondBase.Text) ^ MaxTableSize > Base10Num Then Exit Do<br />
        MaxTableSize = MaxTableSize + 1<br />
        DoEvents<br />
    Loop<br />
    <br />
    ReDim aOutputNum(MaxTableSize)<br />
    <br />
    Dim TableVal As Variant<br />
    Dim TempNum As Double<br />
    Dim OutputStr As String<br />
    TempNum = Base10Num<br />
    For i = 0 To MaxTableSize - 1<br />
        TableVal = Val(SecondBase.Text) ^ (MaxTableSize - i - 1)<br />
        Do<br />
            If Not (TempNum - TableVal) > -1 Then<br />
                Exit Do<br />
            Else<br />
                TempNum = TempNum - TableVal<br />
                aOutputNum(i) = aOutputNum(i) + 1<br />
            End If<br />
            DoEvents<br />
        Loop<br />
    Next i<br />
    <br />
    'make output string<br />
    For i = 0 To MaxTableSize - 1<br />
        OutputStr = OutputStr & ConvertIntoChar(aOutputNum(i))<br />
    Next i<br />
    <br />
    'output, clipping off the leading zeros<br />
    OutputNum.Text = Format$(OutputStr, "########################################")<br />
    <br />
    Exit Sub<br />
    <br />
base10err:<br />
    Debug.Print Err.Description<br />
    If Err.Number = 6 Then 'overflow<br />
        MsgBox "The number to be converted is too large", vbExclamation, "Number Transformer"<br />
    Else<br />
        GoTo defaulterr<br />
    End If<br />
    Exit Sub<br />
    <br />
defaulterr:<br />
    MsgBox Err.Number & vbCrLf & Err.Description, vbExclamation, "Number Transformer"<br />
End Sub<br />
<br />
Private Sub Form_Load()<br />
    Me.Show<br />
    #If FDEBUG = 1 Then<br />
        MsgBox "using conditional compilation!"<br />
    #End If<br />
End Sub<br />
<br />
Public Function ConvertIntoNum10(character As String) As Double<br />
    character = UCase(character)<br />
    Select Case character<br />
    Case "0": ConvertIntoNum10 = 0<br />
    Case "1": ConvertIntoNum10 = 1<br />
    Case "2": ConvertIntoNum10 = 2<br />
    Case "3": ConvertIntoNum10 = 3<br />
    Case "4": ConvertIntoNum10 = 4<br />
    Case "5": ConvertIntoNum10 = 5<br />
    Case "6": ConvertIntoNum10 = 6<br />
    Case "7": ConvertIntoNum10 = 7<br />
    Case "8": ConvertIntoNum10 = 8<br />
    Case "9": ConvertIntoNum10 = 9<br />
    <br />
    Case "A": ConvertIntoNum10 = 10<br />
    Case "B": ConvertIntoNum10 = 11<br />
    Case "C": ConvertIntoNum10 = 12<br />
    Case "D": ConvertIntoNum10 = 13<br />
    Case "E": ConvertIntoNum10 = 14<br />
    Case "F": ConvertIntoNum10 = 15<br />
    Case "G": ConvertIntoNum10 = 16<br />
    Case "H": ConvertIntoNum10 = 17<br />
    Case "I": ConvertIntoNum10 = 18<br />
    Case "J": ConvertIntoNum10 = 19<br />
    Case "K": ConvertIntoNum10 = 20<br />
    Case "L": ConvertIntoNum10 = 21<br />
    Case "M": ConvertIntoNum10 = 22<br />
    Case "N": ConvertIntoNum10 = 23<br />
    Case "O": ConvertIntoNum10 = 24<br />
    Case "P": ConvertIntoNum10 = 25<br />
    Case "Q": ConvertIntoNum10 = 26<br />
    Case "R": ConvertIntoNum10 = 27<br />
    Case "S": ConvertIntoNum10 = 28<br />
    Case "T": ConvertIntoNum10 = 29<br />
    Case "U": ConvertIntoNum10 = 30<br />
    Case "V": ConvertIntoNum10 = 31<br />
    Case "W": ConvertIntoNum10 = 32<br />
    Case "X": ConvertIntoNum10 = 33<br />
    Case "Y": ConvertIntoNum10 = 34<br />
    Case "Z": ConvertIntoNum10 = 35<br />
    End Select<br />
End Function<br />
<br />
Public Function ConvertIntoChar(num10 As Double) As String<br />
    Select Case num10<br />
    Case 0: ConvertIntoChar = "0"<br />
    Case 1: ConvertIntoChar = "1"<br />
    Case 2: ConvertIntoChar = "2"<br />
    Case 3: ConvertIntoChar = "3"<br />
    Case 4: ConvertIntoChar = "4"<br />
    Case 5: ConvertIntoChar = "5"<br />
    Case 6: ConvertIntoChar = "6"<br />
    Case 7: ConvertIntoChar = "7"<br />
    Case 8: ConvertIntoChar = "8"<br />
    Case 9: ConvertIntoChar = "9"<br />
     <br />
    Case 10: ConvertIntoChar = "A"<br />
    Case 11: ConvertIntoChar = "B"<br />
    Case 12: ConvertIntoChar = "C"<br />
    Case 13: ConvertIntoChar = "D"<br />
    Case 14: ConvertIntoChar = "E"<br />
    Case 15: ConvertIntoChar = "F"<br />
    Case 16: ConvertIntoChar = "G"<br />
    Case 17: ConvertIntoChar = "H"<br />
    Case 18: ConvertIntoChar = "I"<br />
    Case 19: ConvertIntoChar = "J"<br />
    Case 20: ConvertIntoChar = "K"<br />
    Case 21: ConvertIntoChar = "L"<br />
    Case 22: ConvertIntoChar = "M"<br />
    Case 23: ConvertIntoChar = "N"<br />
    Case 24: ConvertIntoChar = "O"<br />
    Case 25: ConvertIntoChar = "P"<br />
    Case 26: ConvertIntoChar = "Q"<br />
    Case 27: ConvertIntoChar = "R"<br />
    Case 28: ConvertIntoChar = "S"<br />
    Case 29: ConvertIntoChar = "T"<br />
    Case 30: ConvertIntoChar = "U"<br />
    Case 31: ConvertIntoChar = "V"<br />
    Case 32: ConvertIntoChar = "W"<br />
    Case 33: ConvertIntoChar = "X"<br />
    Case 34: ConvertIntoChar = "Y"<br />
    Case 35: ConvertIntoChar = "Z"<br />
    End Select<br />
End Function<br />
<br />
Private Sub Form_Terminate()<br />
    End<br />
End Sub

GeneralRe: My code Pin
terwin17-Jun-05 6:11
terwin17-Jun-05 6:11 
GeneralRe: My code Pin
new2unix@gmail.com23-Jan-06 3:52
new2unix@gmail.com23-Jan-06 3:52 
GeneralRe: My code Pin
terwin23-Jan-06 3:59
terwin23-Jan-06 3:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.