I want to convert the hex value in the character array
to an integer
.
int main()
{
char arr[5];
arr[0] = 0x05;
int a = atoi(&arr[0]);
cout << "Number = " << a; //output = 0 but i want here value 5
}
I want to convert the hex value in the character array
to an integer
.
int main()
{
char arr[5];
arr[0] = 0x05;
int a = atoi(&arr[0]);
cout << "Number = " << a; //output = 0 but i want here value 5
}
You don't need any conversion at all:
int main()
char arr[5];
arr[0] = 0x05;
int a = arr[0];
}
You don't need any kind of conversion - 0x05
is already an integer value.
If you have a C string which is the textual representation of a number, then 1. you have to NUL-terminate the string, 2. you can use strtol()
(or one member of that family of functions):
char arr[] = "0x05";
int n = strtol(arr, NULL, 0);
atoi has the following signature:
int atoi(const char* buffer);
You are passing a non-null terminated buffer to your function. Also your "character" code value is 0x05 which translates to ACK (acknowledgement). Your number is already 5. Simply:
std::cout << "Number = " << int(arr[0]);
Will give you the result you want.
You assign 0x05 to char, ascii table tells 0x05 can not convert to any number, atoi function returns 0 if no conversion performed. That's why you got output of 0