Converting Binary Digits To Hex

converting 8bit binary into 2 digit hex

Any ideas on how to do this?
im starting it now but going in the direction of using arrays

will be back to post my code

thanks.
Last edited on
Each 4 binary digits can be represented by one hex digit: so 7710 = 100 11012 = 4D16
What you must do depends how you will get your statements. I would just get number in string, parse it by stoi() and output it into string steam using hex manipulator:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    std::string temp;
    std::getline(std::cin, temp);
    int x = stoi(temp, 0, 2);
    std::cout << std::hex << x << std::endl; //To output
    std::stringstream out;
    out << std::hex << x;
    temp = out.str(); //Temp now has number in hex representation
    std::cout << temp;
}

Last edited on
thank you, honestly is meant to do type it the other way around lol

Convert hex to 8 bit binary (stupid me)
i think then you would need to use arrays

,sorry :(
Nope
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <bitset>
#include <sstream>

int main()
{
    std::string temp;
    std::getline(std::cin, temp);
    std::bitset<8> y(stoi(temp, 0, 16));
    std::cout << y << std::endl; //To output
    std::stringstream out;
    out << y;
    temp = out.str(); //Temp now has number in hex representation
    std::cout << temp;
}

Or without bitset and leading zeroes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>

int main()
{
    std::string temp;
    std::getline(std::cin, temp);
    unsigned int x(stoi(temp, 0, 16)); //Do not work with negative values
    std::stringstream y;
    while (x!=0) {
        y << (x&1);
        x >>= 1;
    }
    temp = y.str();
    std::copy(temp.rbegin(), temp.rend(), std::ostream_iterator<char>(std::cout));
}
Last edited on
how would this be done using arrays?
Topic archived. No new replies allowed.