Archived

This topic is now archived and is closed to further replies.

Temer

problem with conversion

Recommended Posts

The conv2hex code isn''t working correctly. I am trying to take the binary stored and convert it to hex. It makes runtime error. the purpose of the program is to convert a neg decimal to a 2''s complement Hex. #include <iostream> #include <cstdlib> #include <cmath> #include <conio.h> using namespace std; #define MAXSIZE 8 #define HEXS MAXSIZE / 4 void conv2comp(int * dest, int num, int neg) { int nextNum = num; int index = MAXSIZE - 1; while( nextNum >= 1 && index >= 0) { dest[index] = nextNum % 2; nextNum/=2; index--; } if(neg) { for(int z = 0; z < MAXSIZE; z++) { if(dest[z] == 1) dest[z] = 0; else dest[z] = 1; } for(int i=0; i < MAXSIZE; i++) { if(dest == 0) { dest[i] = 1; break; } if(dest[i] == 1 ) dest[i] = 0; } } else return; } void conv2hex(int * n, char * p) { int temp = 0; char buffer[2]; int position = 0; int sum = 0; for(int i = 1; i <= HEXS; i++) { for(int j = position; j < (position+4); j++) { cout << position << endl; sum+=n[j] * pow(2, position); } cout << "j: " << j << endl; cout << "sum: " << sum << endl; cout << "position: " << position << endl; cout << "n[j] * pow(2, position) : "<< n[j] * pow(2, position) << endl; getch(); if (sum < 10) { itoa(sum, buffer, 10); p[i] = buffer[0]; } else if( sum == 10) p[i] = ''A''; else if( sum == 11) p[i] = ''B''; else if( sum == 12) p[i] = ''C''; else if( sum == 13) p[i] = ''D''; else if( sum == 14) p[i] = ''E''; else if( sum == 15) p[i] = ''F''; else cerr << "Error..." << endl; position+=4; } } int main() { int buffer[MAXSIZE]; int number; int neg = 0; char buf[2]; for(int k = 0; k < MAXSIZE; k++) buffer[k] = 0; cout << "Enter number(-128 to 127): " << endl; cin >> number; if(number < 0) { neg = 1; number*=-1; } conv2comp( buffer, number, neg); for(int i = 0; i < MAXSIZE; i++) cout << buffer[i]; cout << endl; conv2hex(buffer, buf); for(int index = 0; index < 2; index++) cout << buf[index]; cout << endl; cout << endl; return 0; }

Share this post


Link to post
Share on other sites