mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-02-11 14:36:25 +08:00
fixed decimal to hex
This commit is contained in:
@@ -1,28 +1,34 @@
|
||||
/**
|
||||
* @file
|
||||
* @brief Convert decimal number to hexadecimal representation
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
/**
|
||||
* Main program
|
||||
*/
|
||||
int main(void) {
|
||||
int valueToConvert = 0; // Holds user input
|
||||
int hexArray[8]; // Contains hex values backwards
|
||||
int i = 0; // counter
|
||||
char HexValues[] = "0123456789ABCDEF";
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int valueToConvert = 0; //Holds user input
|
||||
int hexArray[8]; //Contains hex values backwards
|
||||
int i = 0; //counter
|
||||
char HexValues[] = "0123456789ABCDEF";
|
||||
std::cout << "Enter a Decimal Value"
|
||||
<< std::endl; // Displays request to stdout
|
||||
std::cin >>
|
||||
valueToConvert; // Stores value into valueToConvert via user input
|
||||
|
||||
cout << "Enter a Decimal Value" << endl; //Displays request to stdout
|
||||
cin >> valueToConvert; //Stores value into valueToConvert via user input
|
||||
while (valueToConvert > 15) { // Dec to Hex Algorithm
|
||||
hexArray[i++] = valueToConvert % 16; // Gets remainder
|
||||
valueToConvert /= 16;
|
||||
// valueToConvert >>= 4; // This will divide by 2^4=16 and is faster
|
||||
}
|
||||
hexArray[i] = valueToConvert; // Gets last value
|
||||
|
||||
while (valueToConvert > 15)
|
||||
{ //Dec to Hex Algorithm
|
||||
hexArray[i++] = valueToConvert % 16; //Gets remainder
|
||||
valueToConvert /= 16;
|
||||
}
|
||||
hexArray[i] = valueToConvert; //Gets last value
|
||||
std::cout << "Hex Value: ";
|
||||
while (i >= 0) std::cout << HexValues[hexArray[i--]];
|
||||
|
||||
cout << "Hex Value: ";
|
||||
while (i >= 0)
|
||||
cout << HexValues[hexArray[i--]];
|
||||
|
||||
cout << endl;
|
||||
return 0;
|
||||
std::cout << std::endl;
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user