Convert bases decimal, hexadecimal, octal, and binary in C#

convert bases

It’s easy to convert bases if you use the Convert class’s ToInt64 and ToString methods. For example, the following statement parses the text in the TextBox named source and saves the result in the long variable value. The “16” means the method should parse the text as a base 16 (hexadecimal) value.

value = Convert.ToInt64(source.Text, 16);

The following code does the opposite: it converts the value in variable value into a hexadecimal string and displays it in the TextBox named txtHexadecimal.

txtHexadecimal.Text = Convert.ToString(value, 16)

To parse and display values in other bases, simply replace 16 with the base: 8 for octal and 2 for binary.

I told you it was easy!

Download Example   Follow me on Twitter   RSS feed

This entry was posted in mathematics, parsing and tagged , , , , , , , , , , , . Bookmark the permalink.

6 Responses to Convert bases decimal, hexadecimal, octal, and binary in C#

  1. David says:

    Hi guys,
    I use this hex to decimal converter and this decimal to hex converter to convert data
    They are pretty good!
    Hope this help

  2. Jean Hunteni says:

    Some have tried the hex to decimal converter and it seems up to the task. Some even say that they are amazing. Could be useful to try.

    – Jean Hunteni
    Resume working on my Projects.

  3. Doyle says:

    Hey thanks this is awesome! This eliminated so much useless code 🙂

  4. Bryan says:

    Thanks for the source code. You saved my day!

  5. Nikolai Povlsen says:

    I know this is very late but when I use this method: “txtHexadecimal.Text = Convert.ToString(value, 16)”, I get the
    “CS1501 C# No overload for method ‘ToString’ takes 2 arguments”
    error, how can I change this??

    Btw. I am using this code to make a bin, dec, hex & oct converter in WPF C#

    • RodStephens says:

      I don’t know why it would do that. Did you download the example or did you just copy and paste this piece of code into your program? If you copied and pasted, is value a long in your program?

      If you can’t figure it out, email me and I’ll take a look.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.