Home > database >  How to convert Hex in string format to Hex format
How to convert Hex in string format to Hex format

Time:07-08

So i have a code that converts binary input to hex in string format:

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main(){
    string binary[16] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
    char hex[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    string binaryInput;
    cin>>binaryInput;
    int inputLen = binaryInput.length();
    string add(4-inputLen%4,'0');
    if(binaryInput.length()/4!=0){binaryInput = add binaryInput;}
    inputLen = binaryInput.length();
    
    cout<<"converted input: "<<binaryInput<<endl;
    cout<<"converted input length: "<<inputLen<<endl;
    
    int intInput = stoi(binaryInput);
    string hexEq = "";

    for(int i=0;i<inputLen/4;i  ){
        string quad = "";

        for(int k=0;k<4;k  ){
            if(intInput){quad='1' quad;}
            else{quad='0' quad;}
            intInput/=10;
        }

        for(int j=0;j<16;j  ){
            if(quad==binary[j]){
                hexEq = hex[j] hexEq;
                break;
            }
        }
    }

    cout<<"input converted to hex: "<<hexEq<<endl;

} 

(ex. input: 11011, output: 1B)

But i cant figure out how can i represent that in hex format(for ex. i can create hex variables using uint8_t a = 0x1b and print that using printf("%x", a) . I would appreciate if you can help me.

CodePudding user response:

To parse the input, the standard std::stoul allows to set the base as parameter. For base 2:

unsigned long input = std::stoul(str, nullptr, 2);

Than you can print it as hex using either

std::cout << std::hex << input << '\n';

or

std::printf("%lx\n", input);

See https://godbolt.org/z/5j45W9EG6.

  •  Tags:  
  • c
  • Related