user1727270
user1727270

Reputation: 433

48 byte binary to 6 byte binary

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.

Upvotes: 2

Views: 541

Answers (3)

auselen
auselen

Reputation: 28087

#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!");
}

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409136

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.

Upvotes: 3

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

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.

Upvotes: 1

Related Questions