1

I want to make a number appear in the hexadecimal alphabet but I don't know how.

For example I used the number 255.I wanted the number to appear as "FF FF" but it appear as "15 15"

number is the number I want to convert

base is the desired alphabet (bin,dec,oct,hex)

str is the table with the digits

digits is how many digits I have

# include <iostream>
using namespace std;
class Number
{
    private:
        int number; 
        int base;
        int str[80];
        int digits;
        void    convert();

    public:
        Number(int n);
        Number(int n,int b);

printNumber prints the number

        void    printNumber();
};

convert is the function that converts the number

void    Number::convert()
{
    int icount=0;
    int x=number;
    while(x!=0)
    {
        int m=x % base;
        x=x/base;
        str[icount]=m;
        icount=icount+1;
    }

digits count the number of digits I have

    digits=icount;
}

this function uses as base dec

 Number::Number(int n)
{
    number=n;
    base=10;
    convert();
}

this function uses as base an integer b

Number::Number(int n,int b)
 {
    number=n;
    base=b;
    convert();
 }

void    Number::printNumber()
{
    int i;
    for(i=digits-1;i>=0;i--)
      cout<<str[i]<<" ";
     cout<<endl;
}


int main()
{
    Number n1(255);
    Number n2(254,16);
    n1.printNumber();
    n2.printNumber();
    std::cout << "Press ENTER to continue...";
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
    return 0;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
macalex
  • 11
  • 2

3 Answers3

5
#include <iomanip>
#include <iostream>

std::cout << std::hex << number;
clcto
  • 9,530
  • 20
  • 42
0

Change the int str[80]; member to char str[80]. Then change the line str[icount]=m; inside the convert() method to: str[icount]="0123456789abcdef"[m];

Finally ensure the str is zero-terminated, and simply print as a string.

Obviously to just print a hexadecimal value, you could just use the standard library as clcto suggests, but I guess thats not your agenda...

S.C. Madsen
  • 5,100
  • 5
  • 32
  • 50
0

If you want real control on how output is formatted, use the old, C-style printf(). While its syntax is not as intuitive as C++ streams, its far better suited for doing complex stuff. In the case of hex numbers, you would use the x conversion:

#include <stdio.h>

int number = 255;
printf("Here is a hex number: %x\n", number);

The code above will result in the output of

Here is a hex number: ff

Now, if you want to output digital data, you frequently need to output all bits as hex, including leading zeros. Easy with printf():

printf("My int has the bits: 0x%08x\n", number);

which will output

My int has the bits: 0x000000ff
cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106