Reputation: 118
I have a 4 text-represented bytes that i need to divide into 2 bytes (HI and LO byte) and convert it to two integers.
How can i do that in plain C?
0x4b 0xab 0x14 0x9d
By text i mean that they look like "0x4b" not 0x4b.
I already have those string splited into char array, which represents like this:
item[0] = "0x4b";
item[1] = "0xab";
item[2] = "0x14";
item[3] = "0x9d";
Now the finish should look like this:
0x4b 0xab - one integer
0x14 0x9d - second integer
How to do this in Plain C?
Upvotes: 0
Views: 232
Reputation: 6298
This is another approach if you need intermediate results:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
int item1[4];
int item2[2];
char *item[4];
item[0] = "0x4b";
item[1] = "0xab";
item[2] = "0x14";
item[3] = "0x9d";
for (int i = 0; i < 4; i++)
{
item1[i] = strtol ( item[i], NULL, 0 ) ;
printf("%2X\n", item1[i]);
}
for (int i = 0; i < 2; i++)
{
item2[2*i] = (item1[2*i] << 8) | item1[2*i+1];
printf("Received integers: %2X\n", item2[2*i]);
}
return 0;
}
Output:
4B
AB
14
9D
Received integers: 4BAB
Received integers: 149D
Upvotes: 0
Reputation: 50831
You probbaly want this:
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *item[4];
item[0] = "0x4b";
item[1] = "0xab";
item[2] = "0x14";
item[3] = "0x9d";
int value1 = (strtol(item[0], NULL, 0) << 8) | strtol(item[1], NULL, 0);
int value2 = (strtol(item[2], NULL, 0) << 8) | strtol(item[3], NULL, 0);
printf("%x %x", value1, value2);
}
Upvotes: 2