compare two arrays of different types

I want to compare to array. My problem is, that the first array is an array with this structure: 00d5ff4l (a mac-address without colon). The second array is from a buffer. His structure is 00 d5 ff 41 (Hex)

My current code looks like this

char mac[] = "00d5ff4l";
for (int i = 0; i < sizeof(mac); i++) {
    if (mac[i] != other_array[i]) {
        return 0;
    }
    else
        return 1;
}

Now is the problem the following: Index 1 of mac is '0', but for other_array it's '00'. So it will never match in this way. Do i have to cast one of them? If yes, how?

Upvotes: 1

Views: 126

Answers (2)

OVelychko
OVelychko

Reputation: 49

I propose to use if statement only, because mac adress will not changed for several years)) Just create if() conditional for all 8 elements in array. It will be fastest solution without any conversion or loops.

Upvotes: 0

Zakir
Zakir

Reputation: 2382

Here's a little working utility function for you using strncmp

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

int compare_mac() {
    char mac[] = "00d5ff4l";    
    char other_array[] = "00:d5:ff:4l"; //Will work for "00 d5 ff 4l" as well
    int i = 0;
    int j = 0;

    //Bail out early for invalid inputs
    if(strlen(other_array) - strlen(mac) !=3){
        printf("Not Equal");
        return -1;        
    }

    while(i < strlen(mac)){
        if(strncmp(mac+i, other_array+j,2 ) !=0){
            printf("Not Equal");
            return -1;
        }
        i=i+2;
        j=j+3;
    }
    printf("Equal MAC IDs");

    return 0;
}

Discalaimer:- strncmp requires 2 non null pointers. The behavior is undefined when access occurs past the end of either array. The behavior is undefined when either param is a null pointer. So do adequate safety measures if you are taking the char arrays as in params to the function

Upvotes: 1

Related Questions