2

I read a 17 byte hex string from command line "13:22:45:33:99:cd" and want to convert it into binary value of length 6 bytes.

For this, I read a 17 byte hex string from command line "13:22:45:33:99:cd" and converted it into binary digits as 0001 0011 0010 0010 0100 0101 0011 0011 1001 1001 1100 1101. However, since I am using a char array, it is of length 48 bytes. I want the resulting binary to be of length 6 bytes i.e, I want 0001 0011 0010 0010 0100 0101 0011 0011 1001 1001 1100 1101 to be of 6 bytes (48 bits) and not 48 bytes. Please suggest how to accomplish this.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
user1727270
  • 303
  • 1
  • 3
  • 10

3 Answers3

3
#include <stdio.h>

const char *input = "13:22:45:33:99:cd";
int output[6];
unsigned char result[6];
if (6 == sscanf(input, "%02x:%02x:%02x:%02x:%02x:%02x",
                &output[0], &output[1], &output[2],
                &output[3], &output[4], &output[5])) {
    for (int i = 0; i < 6; i++)
        result[i] = output[i];
} else {
    whine("something's wrong with the input!");
}
auselen
  • 27,577
  • 7
  • 73
  • 114
3

Split the string on the ':' character, and each substring is now a string you can pass to e.g. strtoul and then put in a unsigned char array of size 6.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You pack them together. Like high nibble with low nibble: (hi<<4)|lo (assuming both are 4-bits).

Although you may prefer to convert them byte by byte, not digit by digit in the first place.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173