1

I'm building a program that takes input as if it is a bare MAC address and turn it into a binary string. I'm doing this on a embedded system so there is no STD. I have been trying something similar to this question but after 2 days I haven't achieved anything, I'm really bad with these kind of things.

What I wanted is output to be equal to goal, take this into consideration:

#include <stdio.h>

int main() {
    const char* goal = "\xaa\xbb\xcc\xdd\xee\xff";
    printf("Goal: %s\n", goal);

    char* input = "aabbccddeeff";
    printf("Input: %s\n", input);

    char* output = NULL;
    // Magic code here

    if (output == goal) {
        printf("Did work! Yay!");
    } else {
        printf("Did not work, keep trying");
    }
}

Thanks, this is for a personal project and I really want to finish it

2
  • 2
    You need to allocate space to store your output; char *output = NULL: doesn't do that. You need to use strcmp() to compare strings; using == doesn't work (it compares two pointer values; unless you do output = goal; (or goal = output;), the comparison will fail). You've not even shown a basic attempt to convert aa into \xaa. Commented Mar 6, 2018 at 15:36
  • 1
    Possible duplicate of How to convert a char array to a byte array? Commented Mar 6, 2018 at 15:49

1 Answer 1

2

First, your comparison should use strcmp else it'll be always wrong.

Then, I would read the string 2-char by 2-char and convert each "digit" to its value (0-15), then compose the result with shifting

#include <stdio.h>
#include <string.h>

// helper function to convert a char 0-9 or a-f to its decimal value (0-16)
// if something else is passed returns 0...
int a2v(char c)
{
    if ((c>='0')&&(c<='9'))
    {
        return c-'0';
    }
    if ((c>='a')&&(c<='f'))
    {
        return c-'a'+10;
    }
    else return 0;
}

int main() {
    const char* goal = "\xaa\xbb\xcc\xdd\xee\xff";
    printf("Goal: %s\n", goal);

    const char* input = "aabbccddeeff";
    int i;

    char output[strlen(input)/2 + 1];
    char *ptr = output;

    for (i=0;i<strlen(input);i+=2)
    {

       *ptr++ = (a2v(input[i])<<4) + a2v(input[i]);
    }
    *ptr = '\0';
    printf("Goal: %s\n", output);

    if (strcmp(output,goal)==0) {
        printf("Did work! Yay!");
    } else {
        printf("Did not work, keep trying");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, I tested it and it works flawlessly, finally!

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.