开发者

scanf formatting string for hex with dashes

开发者 https://www.devze.com 2023-02-25 12:05 出处:网络
I\'m trying 开发者_JAVA百科to write a C function to parse a MAC address input, with either spaces, colons or dashes as separators. I\'ve been looking into using %*[-:] to match multiple characters but

I'm trying 开发者_JAVA百科to write a C function to parse a MAC address input, with either spaces, colons or dashes as separators. I've been looking into using %*[-:] to match multiple characters but it doesn't seem to be able to detect a white-space character (e.g. a space), and also it produces the wrong values with dashes as it's think that the numbers are negative.

My function looks something like:

scanf("%2x%*[-:]%2x", &hex1, &hex2);

Is it possible in one scanf? Or are there other better ways? Thanks.


I don't know how portable this is, or if it matches your requirements exactly.

#include <stdio.h>

int main()
{
    unsigned a;
    while (scanf("%02x%*[-: ]", &a) == 1) {
        fprintf(stdout, "%02x\n", a);
    }
    return 0;
}

With this input (tab after the first hex number, space before the last):

a0  b1-01:ff-:-b0 55

It produces this output:

a0
b1
01
ff
b0
55

If you need more than one item in the same call, try some variation of (takes spaces or tabs as separators):

#include <stdio.h>

int main()
{
    unsigned a,b,c;
    while (scanf("%02x%*[-: \t]%02x%*[-: \t]%02x%*[:-]", &a, &b, &c) == 3) {
        fprintf(stdout, "%02x %02x %02x\n", a, b, c);
    }
    return 0;
}

Which gives this for the above input:

a0 b1 01
ff b0 55
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号