-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  
}
Pieter VDE
  • 2,195
  • 4
  • 25
  • 44
kks
  • 27
  • 6
  • 2
    You don't need `atoi` – qrdl May 03 '13 at 08:41
  • 1
    `atoi` -> `convert a string to an integer`. So, at this step, `arr[0]= 0x05;` is 0x05 a string/character? No, it's a hex number. Then do you expect atoi work? No. Check this, probably it will help you. http://stackoverflow.com/questions/479373/c-cout-hex-values – abasu May 03 '13 at 08:41
  • but how can i get 5 in the integer variable? – kks May 03 '13 at 08:42
  • `int a = 0xFF; ` this will put the hex value in the int. int is a data type, like a container. `0x` is a base specification, like you are putting water into that container through a garden hose or a glass. But ultimately, only thing that matters is how much water is there. Read K&R – abasu May 03 '13 at 08:47
  • 1
    You're confusing numbers with their representation. `15`, `0x0F`, `017`, `0b1111` are all representations of the same number. You can assign any one of them to a `char` and get the same result. – molbdnilo May 03 '13 at 09:14

4 Answers4

2

You don't need any conversion at all:

int main()
  char arr[5];
  arr[0] = 0x05;
  int a = arr[0];
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

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);
1

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.

Peter R
  • 2,865
  • 18
  • 19
0

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

oohtj
  • 129
  • 5