Search code examples
c++hex24-bit

concatenating a Hexadecimal number with zeros


I have written a simple code to convert a fractional number to 24bit (3 bytes, 6 characters) Hexadecimal number.

Lets say if you enter 0.5, it provides the hexadecimal number as 0x400000.

0.1 = 0xccccd
0.001 = 0x20c5

While the answers are correct, What I'd like to do is preserve the 6 character representation, so i'd like 0.1 to be = 0x0ccccd and
0.001 to be = 0x0020c5.

  1. I thought one possible method would be to convert the hexadecimal result to string and then use strlen to check number of digits and then concatenate the result with the appropriate zeros. The problem I have with this method is I'm not sure how to store the hex result in a variable.
  2. I figured even if I convert the Hex number to string and find the number of zeros to concatenate, the program would be a bit clunky. There just might be a simpler way to achieve what I want to do. I just don't know how. Hoping someone can show me the way forward. The program I wrote is below.
while(true){
    float frac_no;
    std::cout << "Enter a fractional number(0-1) or press 0 to exit:";
    std::cin >> frac_no;    
    if(!frac_no){
        break;
    }

    const int max_limit_24 = exp2(23);   // The maximum value of 0x7FFFFF(1.0)

    float inter_hex;

    inter_hex = round(max_limit_24*frac_no);
    int int_inter_hex = int(inter_hex);
    std::cout << std::hex << "0x" << int_inter_hex  << "\n" ;
}

Solution

  • #include <iomanip>
    int val = 0x20c5;
    std::cout << "0x" << std::setw(6) << std::hex << std::setfill('0') << val << '\n';
    

    If you just need it to have the leading 0s on output. If you do want to store it as a string, you can use an std::stringstream instead of std::cout and get the string from it.