0

I'm trying to extract 2nd and 3rd byte from a char array and interpret it's value as an integer. Here in this case, want to extract 0x01 and 0x18 and interpret its value as 0x118 or 280 (decimal) using strtol. But the output act len returns 0.

int main() {

char str[]={0x82,0x01,0x18,0x7d};
char *len_f_str = malloc(10);
int i;
memset(len_f_str,'\0',sizeof(len_f_str));

strncpy(len_f_str,str+1,2);

printf("%x\n",str[1] & 0xff);
printf("%x\n",len_f_str[1] & 0xff);
printf("act len:%ld\n",strtol(len_f_str,NULL,16));

return 0;
}

Output:

bash-3.2$ ./a.out 
1
18
act len:0

What am I missing here? Help appreciated.

user967850
  • 31
  • 6
  • `strtol` doesn't work the way you are expecting it to be used. It works on alphanumeric strings (cf. `isalnum`/`isdigit`). – ldav1s May 22 '14 at 00:06
  • Also `sizeof(len_f_str)` most propably returns 4 (for 32bit systems) and 8 (for 64bit system) as it returns the size of the pointer `len_f_str`. It does **not** return the size of memory allocted to it, that is 10. – alk May 22 '14 at 05:57

2 Answers2

1

strtol converts an ASCII representation of a string to a value, not the actual bits.

Try this:

short* myShort;
myShort = (short*) str[1];
long myLong = (long) myShort;
Peter Gluck
  • 8,168
  • 1
  • 38
  • 37
0

strtol expects the input to be a sequence of characters representing the number in a printable form. To represent 0x118 you would use

char *num = "118";

If you then pass num to strtol, and give it a radix of 16, you would get your 280 back.

If your number is represented as a sequence of bytes, you could use simple math to compute the result:

unsigned char str[]={0x82,0x01,0x18,0x7d};
unsigned int res = str[1] << 8 | str[2];
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523