DEC to HEX Please help

Hello i have made this code, but i wanted to print it out in Hexadecimal format, but i cant figure it out. Any help will be welcomed. By the way i dont understand the conversion to Hexa.

And i cant use include for conversion...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  #include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int noob;
    do
    {
    const int numwidth=3;
    int  b=1, i=1, dec;
    do
    {
        dec=i*b;
        cout<<setw(numwidth)<<dec<<" ";
        i++;
        if(i==17)
        {
        cout<<endl;
         b++;
         i=1;
        }
    }while(b<17);
    cout << "Do you wish to continue(0=No, 1=Yes)"<<endl;
    cin >> noob;
    }while(noob==1);

}
Last edited on
1
2
3
4
5
6
7
8
#include <iostream>
#include <iomanip>

int main()
{
    int dec = 42;
    std::cout << std::hex << dec;
}
2a
1
2
3
4
5
6
7
int main()
{
    cout.unsetf(cout.dec);
    cout.setf(cout.hex);
    int x = 42;
    cout << x;
}

Last edited on
Is there a way without use of these commands? I just want to understand the logic behind it

 
dec%16


Would it work for these numbers?
well you could try doing the algorithm for changing number systems(. Basically, you try to divide the number by the base system(in this case ,16) until it becomes less than that base(16). for example(pseudocode ONLY):
int base = 16;
int conv = 0;
while(number > 15)///because it is 0 to 15 or 0 to F
{
number /= 16;
if(
////convert the conv from 10 to 15 to A to F, use % here to get fractional part say fractional part is 10, therefore it is A in hex
}

hope it helps. :)
Thanks i got it to work but i have another problem, when i enter 300 it prints out C21, but it should print out 12C, how can i switch it? Sorry if this is very simple, just now started C++
The first output of the loop(as I posted above) is the LSB (Least Significant Bit). This means that the first output would be located at the last digit of the number(say, ones digit) and going to MSB(Most Significant Bit), which is of course, the leftmost part. So assuming you are using an array of char:

for(unsigned int i = 0;i<sizeof(conv);i++)
{
std::cout<<conv[i];
}

or in reverse:

for(unsigned int i = sizeof(conv);i>=0;i++)
{
std::cout<<conv[i];
}


That should help. :)
Last edited on
Topic archived. No new replies allowed.