How to Convert ASCII to Binary and Hexadecimal and vice versa with C++
Easily and quickly.
Several times we need to convert our data to manipulate it in the desired way and even to make it difficult to display when necessary.
For development purposes, it’s good to have something ready to go faster, so I created a single
convert.hpp file with a Union which has the member functions for this.
I really don’t like to fill the code with comments, because programmers know how to read the code of the programming language that it is acquainted.
However, I will inform some things in the code to make it easier to read and if you want to increment something, it will be easier, they are:
structfor performance reasons as we saw in this article;
- I’ve assigned
staticso we don’t need an instance and can be used more easily with the
- I didn’t enter
staticitself will allow a scope;
- Although the default for classes, unions and structs is to have capitalized names, I didn’t use them because I think that, typographically in this case it’s more pleasant;
- I used the class std::bitset, writing from scratch is good for didactic purposes, for development it is good to use solutions already ready;
- In the member function
ascii_to_bin()I added this check below just to separate the output into 8 bits, example:
01010101 01010101, that is, by a space in the middle:
- In the
bin_to_hex()member function I added the iterator
bin.erase( std::remove( bin.begin() , bin.end(), ' ') , bin.end() );to we remove the white space from the bits, if any, as in
bin_to_ascii()the conversions are different;
- When reading the code also note that for hexadecimal it is necessary to use the template of 16 instead of
- And finally the
ascii_to_hexmember function, reuses the other member functions, not having to rewrite everything.
The complete code is this:
To use it, just include this file and call the static member functions of the union, for example:
Possible and probable output:
If you want to add more conversions, for example to: decimal and octal, it will be a good exercise. I didn’t put it on GitHub because it’s just a basic file! 😃