关于我遇到的c问题,我有一个基本的问题。我的输入字符数组如下所示:
'DABC95C1'
我想用它做一个uint8_t数组
0xDA 0xBC 0x95 0xC1
我可以很容易地访问每个字符,但我不知道如何形成0xDA。在c中有没有函数,或者我可以直接转换它?
发布于 2018-05-28 22:58:47
按所选顺序排列的任意大小字符串。可移植的数字转换,它在ASCII系统上优化得非常好。https://godbolt.org/g/Ycah1e
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int CharToDigit(const char c);
void *StringToTable(const char *str, const void *buff, const int order)
{
uint8_t *ptr = (uint8_t *)buff;
size_t len;
int incr = order ? 1 : -1;
if(buff && str)
{
len = strlen(str);
if(len &1) return NULL;
ptr += order ? 0 : len / 2 - 1;
while(*str)
{
int d1 = CharToDigit(*str++);
int d2 = CharToDigit(*str++);
if(d1 == -1 || d2 == -1) return NULL;
*ptr = d1 * 16 + d2;
ptr += incr;
}
}
return buff;
}
int main(void) {
int index = 0;
char *str = "78deAc8912fF0f3B";
uint8_t buff[strlen(str) / 2];
StringToTable(str, buff, 0);
printf("String: %s\nResult: ", str);
for(index = 0; index < strlen(str) / 2; index++ )
{
printf("[0x%02hhx]", buff[index] );
}
printf("\n");
StringToTable(str, buff, 1);
printf("String: %s\nResult: ", str);
for(index = 0; index < strlen(str) / 2; index++ )
{
printf("[0x%02hhx]", buff[index] );
}
printf("\n");
return 0;
}
int CharToDigit(const char c)
{
switch(c)
{
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
default:
return -1;
}
}
发布于 2018-05-28 22:28:00
您可以将字符转换为int类型,如下所示
static inline int char2int(char Ch)
{
return(Ch>='0'&&Ch<='9')?(Ch-'0'):(Ch-'A'+10);
//assuming correct input with no lowercase letters
}
两个字符,然后使用
static inline
int chars2int(unsigned char const Chars[2])
{
return (char2int(Chars[0])<<4)|(char2int(Chars[1]));
}
通过转换每对字符和几个字符:
static inline int char2int(char Ch)
{
return(Ch>='0'&&Ch<='9')?(Ch-'0'):(Ch-'A'+10);
}
static inline
int chars2int(unsigned char const Chars[2])
{
return (char2int(Chars[0])<<4)|(char2int(Chars[1]));
}
#include <stdio.h>
#include <string.h>
#include <assert.h>
int main()
{
char const inp[] = "DABC95C1";
assert((sizeof(inp)-1)%2==0);
unsigned i;
unsigned char out[(sizeof(inp)-1)/2];
for(i=0;i<sizeof(inp);i+=2){
out[i/2]=chars2int((unsigned char*)inp+i);
}
for(i=0;i<sizeof(out);i++)
printf("%2x\n", out[i]);
}
https://stackoverflow.com/questions/50568238
复制相似问题