How to convert string with binary number to hex in C++

2 Answers

0 votes
#include <iostream>
#include <string>

std::string BinaryToHex(std::string str) {
    long long decimalNumber = std::stoll(str, nullptr, 2);
    std::string hexString = "";
    
    while (decimalNumber > 0) {
        int remainder = decimalNumber % 16;
        char hexDigit;
        if (remainder < 10) {
            hexDigit = static_cast<char>(remainder + '0');
        } else {
            hexDigit = static_cast<char>(remainder - 10 + 'A');
        }
        hexString = hexDigit + hexString;
        decimalNumber /= 16;
    }
    
    return hexString;
}

int main() {
    std::string binaryNumber = "111101001101";
    
    std::string hex = BinaryToHex(binaryNumber);
    
    std::cout << hex << std::endl;
}

 
 
 
/*
run:
 
F4D
 
*/

 



answered Jul 1, 2024 by avibootz
0 votes
#include <iostream>
#include <string>
#include <sstream>

std::string BinaryToHex(const std::string& str) {
    long decimalNumber = std::stol(str, nullptr, 2);
    std::ostringstream hexStream;
    hexStream << std::hex << decimalNumber;
    
    return hexStream.str();
}

int main() {
    std::string binaryNumber = "111101001101";
    
    std::string hex = BinaryToHex(binaryNumber);
    
    std::cout << hex << std::endl;
}

 
 
 
/*
run:
 
f4d
 
*/

 



answered Jul 1, 2024 by avibootz

Related questions

1 answer 185 views
1 answer 164 views
1 answer 149 views
1 answer 132 views
1 answer 151 views
1 answer 113 views
1 answer 140 views
...