Decimal to hexadecimal converter
Hi everyone. Im trying to make decimal to hexadecimal converter. The code is given below:
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 30 31 32 33 34 35 36 37 38
|
#include<iostream>
#include<cstring>
using namespace std;
void hexadecimal(int x);
int main()
{
int num;
cout<<"Enter a number"<<endl;
cin>>num;
hexadecimal(num);
system("pause");
return 0;
}
void hexadecimal(int x)
{
int rem, qou;
string hex[10];
for(int i=0 ; i<10 ; i++)
hex[i] = "\n";
qou = x/16;
cout<<qou;
rem = x%16;
hex[0] = qou;
for(int i=1 ; i<=rem ; i++)
{
qou = x/16;
rem = x%16;
hex[i]= qou;
}
for(int i=0 ; hex[i] != "\n" ; i++)
{
cout<<hex[i]<<endl;
}
}
|
i know im doing it wrong. can anyone help me to do it right.And at line 33 and 35 != and << operators are also not working. can anyone here explain???
try this. haven't tested it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
void hexadecimal(int x)
{
string hex[10];
int index = 0; // position to insert in hex
do {
rem = x%16;
if (rem > 9)
hex[index] = 'A' + rem - 10;
else
hex[index] = '0' + rem;
index++;
x /= 16;
} while (x);
for(int i=index-1 ; i>=0 ; i--)
{
cout << hex[i];
}
cout << endl;
}
|
EDIT: Bit operations would be more efficient.
instead of
rem = x % 16;
you can do
rem = x & 15;
instead of
x /= 16;
you can do
x >> 4;
Last edited on
at line 16 insertion operator is not working....
You don't need an array of strings. Use either a single string, or an array of characters.
char hex[10];
Two approaches:
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
std::string as_hex( unsigned value )
{
const char* digits = "0123456789ABCDEF" ;
std::string num("0x") ;
unsigned hexDigits = std::numeric_limits<unsigned>::digits / 4 ;
unsigned i=0;
unsigned byteMask = 0xF << (hexDigits-1)*4 ;
// skip leading 0's
while ( i < hexDigits && (byteMask & value) == 0 )
{
byteMask >>= 4 ;
++i ;
}
while ( i < hexDigits )
{
unsigned digit = (byteMask & value) >> 4*(hexDigits-i-1) ;
num += digits[digit] ;
byteMask >>= 4 ;
++i ;
}
if ( num.length() == 2 )
num += '0' ;
return num ;
}
int main()
{
int num ;
std::cout << "Enter a number: " ;
std::cin >> num ;
std::cout << std::showbase ;
std::cout << num << " is " << std::hex << num << '\n' ;
std::cout << std::dec << num << " is " << as_hex(num) << '\n' ;
}
|
Topic archived. No new replies allowed.