将十六进制字符转换为整数 - 有更好的方法吗?
我编写了一个函数来接收来自 Sirit IDentity MaX AVI 阅读器的数据并解析出设施代码和钥匙卡号码。我目前的做法是有效的,但是有更好的方法吗?看起来有点老套... buff & buf 的大小为 264
buf
和 buff
是 char
从阅读器接收的数据:
2009/12/30 14:56:18 epc0 LN:001 C80507A0008A19FA 0000232F Xlat'd
char TAccessReader::HexCharToInt(char n)
{
if (n >= '0' && n <= '9')
return (n-'0');
else
if (n >= 'A' && n <= 'F')
return (n-'A'+10);
else
return 0;
}
bool TAccessReader::CheckSirit(char *buf, long *key_num, unsigned char *fac) {
unsigned short i, j, k;
*key_num = 0; // Default is zero
memset(buff, 0, sizeof(buff));
i = sscanf(buf, "%s %s %s %s %s %s %s", &buff[0], &buff[20], &buff[40],
&buff[60], &buff[80], &buff[140], &buff[160]);
if (i == 7 && buff[147] && !buff[148]) {
// UUGGNNNN UU=spare, GG=Facility Code, NNNN=Keycard Number (all HEX)
// get facility code
*fac = HexCharToInt(buff[142]) * 16 + HexCharToInt(buff[143]);
*key_num = (unsigned short)HexCharToInt(buff[144]) * 4096 +
(unsigned short)HexCharToInt(buff[145]) * 256 +
(unsigned short)HexCharToInt(buff[146]) * 16 +
HexCharToInt(buff[147]);
}
// do some basic checks.. return true or false
}
I have written a function to take in the data from a Sirit IDentity MaX AVI reader and parse out the facility code and keycard number. How I am currently doing it works, but is there a better way? Seems little hackish... buff & buf are size 264
buf
and buff
are char
Data received from reader:
2009/12/30 14:56:18 epc0 LN:001
C80507A0008A19FA 0000232F Xlat'd
char TAccessReader::HexCharToInt(char n)
{
if (n >= '0' && n <= '9')
return (n-'0');
else
if (n >= 'A' && n <= 'F')
return (n-'A'+10);
else
return 0;
}
bool TAccessReader::CheckSirit(char *buf, long *key_num, unsigned char *fac) {
unsigned short i, j, k;
*key_num = 0; // Default is zero
memset(buff, 0, sizeof(buff));
i = sscanf(buf, "%s %s %s %s %s %s %s", &buff[0], &buff[20], &buff[40],
&buff[60], &buff[80], &buff[140], &buff[160]);
if (i == 7 && buff[147] && !buff[148]) {
// UUGGNNNN UU=spare, GG=Facility Code, NNNN=Keycard Number (all HEX)
// get facility code
*fac = HexCharToInt(buff[142]) * 16 + HexCharToInt(buff[143]);
*key_num = (unsigned short)HexCharToInt(buff[144]) * 4096 +
(unsigned short)HexCharToInt(buff[145]) * 256 +
(unsigned short)HexCharToInt(buff[146]) * 16 +
HexCharToInt(buff[147]);
}
// do some basic checks.. return true or false
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用
std::stringstream
:您也可以使用
strtol
来自直接 C:Just use
std::stringstream
:You can also use
strtol
from straight-up C:这是获取所需数据的简单方法。我从事访问控制业务,所以这是我感兴趣的事情......
Here's an easy way to get at the data you want. I do work in the access control business so this was something that interested me...
既然您已经在使用 sscanf,为什么不让它为您解析十六进制数字:
Since you are already using sscanf, why not have it parse the hex numbers for you: