Issue with code

I'm trying to make a code that converts all decimal numbers between 1-255 to hexadecimal. From the looks of this code, it seems to be fine, however, it continues to give an error without a reasoning. I'm getting frustrated, I don't know where the problem is.

Can anyone spot the problem?

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
#include <iostream>
#include <string>
using namespace std;

int main()
{
	int r[10];
	int x = 0, j = 0;

	for (int z = 0; z < 256; z++)
	{
		while (z > 0)
		{
			r[x] = z%16;
			z = z/16;
			x++;
			j++;
		}
	}

	for (x = j - 1; x >= 0; x--)
	{
		if (r[x] == 10)
		cout << "A";
		else if(r[x] == 11)
		cout << "B";
		else if(r[x] == 12)
		cout << "C";
		else if(r[x] == 13)
		cout << "D";
		else if(r[x] == 14)
		cout << "E";
		else if(r[x] == 15)
		cout << "F";
		else
		cout << r[x];	
	}
	cout << "\n";

	system("pause");
}
Last edited on
Here is your program. Actually, I couldn't use most of it. I took the liberty of adding in a request for a decimal number, then out-putting the hex value. If you need to write out all 256 values, just create a for loop, though you'll have to scroll through the screen, to see them all.
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
// Dec to Hex.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string r[256][2];
	string Hex[16] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
	int x = 0;

	for (int z = 0; z < 256; z++)
	{
			x = z%16;
			r[z][1] = Hex[x];
			x = z/16;
			r[z][0] = Hex[x];
	}
	do
	{
	cout << "Please enter a decimal number (  0 to 255 )\n";
	cin >> x;
	if ( x<0||x>255)
		break;
	cout << "The hex value for " << x << " is " << r[x][0] << r[x][1]<< "\n\n";
	} while ( x <= 255  );
	
	system("pause");
}
Last edited on
FYI, STL streams already can convert to HEX, and this includes the standard output cout:

cout << hex << 240;

FYI #2: The easiest algorithm is a recursive one. Try it out.
Topic archived. No new replies allowed.