Tuesday, December 15, 2009

Converting Decimal/Hex/Octal to Binary in C++

I needed to code a hex to binary converter in C++. It was needed for a Verilog parser. There are lots of examples that one can find on google. I decided to code mine, and I also added decimal and octal numbers. The aim is to convert a Verilog constant (hex/octal/decimal) to a std::string of 1,0,X,Z values.

Let's start with decimal to binary:


The function will return the number of bits asked by the user. Of course, this function cannot handle X or Z values supported by Verilog. It worked for me.

For hex to binary and octal to binary conversions, I decided to use simple macros because it turned out to be the fastest code I tried. It does not look elegant, but that is not a concern for me.

First define the macros:

In these macros, HEX and OCT are characters, and STRING is an std::string. I used these macros in the following way:







No comments:

Post a Comment