You are here:

C++/checking for characters

Advertisement


Question
Hi, I am trying to write a program that checks for the correct address of a
MAC address. I'm trying to figure out how to ask the computer if all the
semicolons/characters are in the same place. I'm sure there has to be an
easier way then checking all 16 digits. So I guess my question is how do I
best check the format of MAC addresses (also, everything has to be 0-9 or a-
f and I'm not sure how to deal with that). Thanks so much!

Answer
If you assume the format is:

hh:hh:hh:hh:hh:hh

then you might want to sit in a loop checking for the 6 hh's and the colons.  I'd do the following:

#include <stdio.h>
#include <ctype.h>

char  *MAC = "12:34:56:78:9A:BC";

bool  checkHex( const char *ptr )
{
return *ptr >= '0' && *ptr <= '9' || toupper( *ptr ) >= 'A' && toupper( *ptr ) <= 'F';
}

bool  checkMAC( const char *ptr )
{
for( int count = 0; count < 6; ++count, ++ptr )
 {
 if(checkHex(ptr++) == false)
   break;
 if(checkHex(ptr++) == false)
   break;
 if( *ptr && *ptr != ':' )
   break;
 }
return count == 6;
}

void main( void )
{
 printf( "MAC address is %s\n", checkMac( MAC ) ? "good" : "bad" );
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.