2

我想将一个字符串,比如“00-00-CA-FE-BA-BE”转换为 unsigned char ch[6] 数组。我尝试过使用sscanf,但由于变量 macAddress 后的堆栈损坏,无论出于何种原因,它都会崩溃。

我猜格式说明符有一些问题,但我似乎无法正确理解。

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

char string1[] = "00-00-CA-FE-BA-BE";
char seps[]   = "-";
char *token1 = NULL;
char *next_token1 = NULL;

int main( void )
{
    unsigned char macAddress[6];
    unsigned char ch;
    int idx=0;
    printf( "Tokens:\n" );

    // Establish string and get the first token:
    token1 = strtok_s( string1, seps, &next_token1);

    while ((token1 != NULL))
    {
        sscanf_s(token1, "%02X", &macAddress[idx++], 1);
        printf(" idx %d : %x\n", idx, macAddress[idx-1]);
        token1 = strtok_s( NULL, seps, &next_token1);
    }
}

如果有人能找到问题或提出替代方案,我会很高兴。

4

3 回答 3

5

%X 格式说明符用于整数,而不是字符。您需要将整数变量的地址传递给sscanf_s稍后将其值分配给字符的值。

于 2013-09-07T05:11:41.307 回答
1

在 C++ 中,我可能会使用字符串流,如下所示:

#include <vector>
#include <string>
#include <sstream>
#include <iostream>

int main() {
    std::vector<unsigned char> macAddress;

    std::istringstream input("00-00-CA-FE-BA-BE");

    unsigned int temp;

    // read first byte of input.
    input >> std::hex >> temp;

    do {
        // save current byte
        macAddress.push_back((unsigned char) temp);
        // ignore separator
        input.ignore(1);
        // read next byte:
    } while (input >> std::hex >> temp);

    // show what we read:
    for (auto ch : macAddress)
        std::cout << std::hex << (unsigned int) ch << ":";
}
于 2013-09-07T05:15:41.717 回答
0

将 MAC 地址扫描到 6 的数组中unsigned char

const char string1[] = "00-00-CA-FE-BA-BE";
unsigned char macAddress[6];
char c;
int n;
n = sscanf(string1, "%hhX-%hhX-%hhX-%hhX-%hhX-%hhX %c", &macAddress[0],
        &macAddress[1], &macAddress[2], &macAddress[3], &macAddress[4],
        &macAddress[5], &c);
if (n == 6) {
  printf("%02X-%02X-%02X-%02X-%02X-%02X\n", macAddress[0], macAddress[1],
          macAddress[2], macAddress[3], macAddress[4], macAddress[5]);  // 00-00-CA-FE-BA-BE
} 
else {
  printf("Oops %d\n", n);
}
于 2013-09-07T05:37:48.280 回答