将十六进制字符串转换为unsigned char []

时间:2013-09-07 05:05:13

标签: c windows

我想将一个字符串,比如“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);
    }
}

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

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

在C ++中,我可能会使用stringstream,如下所示:

#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 << ":";
}

答案 2 :(得分: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);
}