Ç - 格式化的MAC地址 [英] C - formatting MAC address

查看:141
本文介绍了Ç - 格式化的MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在与一些解析MAC地址的工作。我给出的输出不包括前导零(像这样)。

I am currently working with parsing some MAC addresses. I am given an output that does not include leading zeros (like so).

char* host = "0:25:25:0:25:25";

和我想,像这样进行格式化

and I would like to format it like so

char* host = "00:25:25:00:25:25";

什么是去了解最简单的方法?

What would be the easiest way to go about this?

对于那些想知道,我现在用的是libpcap的图书馆。

For those wondering, I am using the libpcap library.

推荐答案

我可能会丢失在问题的东西。假设你知道这是一个有效的MAC,输入字符串是这样解析的,你有没有考虑简单的东西如:

I may be missing something in the question. Assuming you know it is a valid MAC, and the input string is thus parsable, have you considered something as simple as:

char* host1 = "0:25:25:0:AB:25";
char *host2 = "0:1:02:3:0a:B";
char result[19];
int a,b,c,d,e,f;

// the question sample
if (sscanf(host1, "%x:%x:%x:%x:%x:%x", &a,&b,&c,&d,&e, &f) == 6)
    sprintf(result, "%02X:%02X:%02X:%02X:%02X:%02X", a,b,c,d,e,f);
printf("host1: %s\n", result);

// a more daunting sample
if (sscanf(host2, "%x:%x:%x:%x:%x:%x", &a,&b,&c,&d,&e, &f) == 6)
    sprintf(result, "%02X:%02X:%02X:%02X:%02X:%02X", a,b,c,d,e,f);
printf("host2: %s\n", result);

输出

host1: 00:25:25:00:AB:25
host2: 00:01:02:03:0A:0B

显然,对于超偏执,你会希望确保 A-F 都是< 255,这可能是preferable。最根本的原因,我preFER这种性能不是一个关键问题是的你可能不会在你的问题考虑的事情。它可以处理所有的

Obviously for the ultra-paranoid you would want to make sure a-f are all < 255, which is probably preferable. The fundamental reasons I prefer this where performance isn't a critical issue are the many things you may not be considering in your question. It handles all of


    N的
  1. 铅值,其中 N 取值的任何的十六进制数字;不只是零。例如:5:0

  2. 中旬值:N:,再次在相同的条件为:(1)上述之下。例如::A:0:

  3. 尾值:N。再次,相同的条件(1)以上下。例如::B:0

  4. 十六进制数字无关时看书;它的工作原理与两个大写和小写数字字符。

  5. 最重要的是,什么也不做(除了大写十六进制丘壑),如果你输入的字符串已正确格式化。

  1. Lead values of "n:", where n s any hex digit; not just zero. Examples: "5:", "0:"
  2. Mid values of ":n:", again under the same conditions as (1) above. Examples: ":A:", ":0:"
  3. Tail values of ":n". once more, under the same conditions as (1) above. Examples: ":b", ":0"
  4. Hex-digit agnostic when reading; it works with both upper and lower case digit chars.
  5. Most important, does nothing (except upper-case the hex vals) if you're input string is already properly formatted.

这篇关于Ç - 格式化的MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆