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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

8 Comments

-1 Actually. This isn't right. First, %x is for ints, not chars. Second, char may be a signed type and therefore a value such as 0xFF will be outside of the range of char, causing signed overflow, which, in turn is undefined behavior.
@AlexeyFrunze noticed that. fixed.
@MichaelKrelin-hacker why 6? why not 17?
@auselen, scanf-family functions return the number of items assigned, no?
@MichaelKrelin-hacker feel free to edit the post, I didn't get what you mean.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.