hex to dec. c++ codes?

please help, there seems to be an error here

#include "stdafx.h"

#include <iostream>

#define BUFF 8

using namespace std;

int main () {

int num;

char input[BUFF];

cout<< "Enter a hexadecimal number: ";

cin>> input;

int answer = hex2int (input, strlen(input));

cout<< "Converting... \n\n";

cout<< "Decimal equivalent is: " << answer << endl << endl;

system ("pause");

return 0;

}

unsigned long hex2int(char *a, unsigned int len)

{

int i;

unsigned long val = 0;

for(i=0;i<len;i++)

if(a[i] <= 57)

val += (a[i]-48)*(1<<(4*(len-1-i)));

else

val += (a[i]-55)*(1<<(4*(len-1-i)));

return val;

}

HOW DO I CORRECT IT

please do rewrite the right codes.

Comments

  • Since you said "rewrite"

    #include <iostream>

    #include <string>

    int main()

    {

         std::cout << "Enter a hexadecimal number: ";

         unsigned long answer;

         std::cin >> std::hex >> answer;

         std::cout << "Converting... \n\n";

         std::cout << "Decimal equivalent is: " << answer << "\n\n";

    }

    test: https://ideone.com/dL49O

    as for the things you did wrong:

    1. you're reading with "cin >>" into an array, that makes your program extremely vulnerable to any malicious user. It will execute any code I input after the 8th symbol.. >> is for strings, numbers, etc, but if you must write to an array, use cin.getline()

    3. you didn'r declare hex2int before use

    4. you didn't use the debugger mode to step through hex2int to see where it goes wrong.

  • please refer-

    daniweb.com/software-development/c/threads/188797

Sign In or Register to comment.