简体   繁体   中英

4-bit Binary to Hexadecimal converter (C++ beginner)

I'm trying to write a code that prompts the user to enter a binary number ranging from 0000 to 1111 and converting it to hexadecimals. If it is outside that range or is not in 4-bit binary, a failure message should show. The only problem is that I'm a complete beginner in C++ and this assignment is a bit out of my reach. So far all I've done is this:

string bit;
bit.length() = 4;

cout<<"Enter number: ";
cin>>bit;

std::cout << std::hex <<bit;

I've found this line after some researching std::cout << std::hex but I don't know if I'm using it right. I'm really out of ideas, any hints to guide me in the right direction would be really appreciated:)

This is quite simple to achieve with strtol , which accepts a parameter specifying the base to use. You can combine this with some basic input-checking to ensure all your characters are binary digits.

Then, once you've read the binary value as an integer, you can output with std::hex manipulator.

#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <string>

int main()
{
    std::string line;
    while (std::getline(std::cin, line))
    {
        if (!line.empty() &&
            std::all_of(line.begin(), line.end(),
                [](char c) {
                    return c == '0' || c == '1';
                }))
        {
            long value = std::strtol(line.c_str(), NULL, 2);
            std::cout << std::hex << value << '\n';
        }
    }
}

Input:

0110
1001
ignore me
0100
0010
0000
10111010101011011111000000001101

Output:

6
9
4
2
0
baadf00d

If you only want to allow exactly 4-bits of input, then change the .line.empty() check to line.size() == 4 .

Alternatively, you can use std::unordered_map or similar to create a mapping of your strings directly to a hex character and then do a lookup. You could even just store an array of the 16 possible strings and binary-search it to get the index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM