Home > database >  C : library for conversion, Ex: binary -> decimal | binary -> hexadecimal etc
C : library for conversion, Ex: binary -> decimal | binary -> hexadecimal etc

Time:09-26

for my project i need to convert some numbers, exemple:

  1. Binary --> decimal
  2. Decimal--> binary
  3. Binary --> hexadecimal
  4. Hexadecimal --> binary
  5. Etc...

I tried to create some functios, but it's long operation and i immediately need a converter.

Someone know a library for do this, then, where do i find it.

CodePudding user response:

You can use stoi function to convert values in binary/hex/octal format to decimal number:

#include <iostream>
#include <string>

int main() {
  std::string hex("BAF");
  std::string bin("1111");
  std::string octal("734");

  std::cout << "Hex: " << hex << " => " << std::stoi(hex, 0, 16) << std::endl;
  std::cout << "Bin: " << bin << " => " << std::stoi(bin, 0, 2) << std::endl;
  std::cout << "Octal: " << octal << " => " << std::stoi(octal, 0, 8)
            << std::endl;
}

For other conversions (from decimal to binary/hex/octal) you should implement your own function. You can use std::bitset to help you with that.

CodePudding user response:

Example some steps involving strings and numbers

#include <iostream>
#include <bitset>
#include <cassert>
#include <string>
#include <sstream>

int main()
{
    auto binary = std::stoi("0110", nullptr, 2);
    auto hex = std::stoi("f", nullptr,  16);

    assert(binary == 6);
    assert(hex == 15);

    std::stringstream os;

    os << std::hex << hex;  // todo add formatters.
    std::cout << os.str() << std::endl;

    std::bitset<4> bits{ binary };
    std::cout << bits.to_string() << std::endl;

    return 0;
}
  • Related