简体   繁体   English

在C中,如何将char *转换为十六进制

[英]In C, How to convert char* to hex

I have extracted a MAC address into a char* array such that each section of the array is a pair of char values. 我已经将MAC地址提取到char*数组中,这样数组的每个部分都是一对char值。

mac[0] = "a1"
mac[1] = "b2"
...
mac[5] = "f6"

Basically I need to take the char arrays and convert them to an unsigned char such that the hex representation is the same as the original char values. 基本上我需要取char数组并将它们转换为unsigned char,这样十六进制表示与原始char值相同。

a1 in ascii -> 0xa1

What is the best way to convert char* to hex in C? 在C中将char *转换为十六进制的最佳方法是什么?

My C isn't the best, but this works using strtol(start, [stop], base) 我的C不是最好的,但这可以使用strtol(start,[stop],base)

#include <stdlib.h>
#include <stdio.h>

int main(char ** argv, int argc) {
  char * input = "a1";
  printf("%d\n", (unsigned char)strtol(input, NULL, 16));
}
#include <stdlib.h>
#include <stdio.h>

unsigned char mac_uchar[6];

for(i = 0;i < 6; ++i) {
    mac_uchar = (unsigned char) strtol (&mac[n], (char **) NULL, 16);
}

I was slow in answering... 我回答得很慢......

You can use sscanf for this purpose. 您可以使用sscanf来实现此目的。

int mac_byte;
unsigned char byte;
sscanf(mac[0],"%x",&mac_byte);
byte = mac_byte & 0xFF;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM