gpt4 book ai didi

检查 charArray 是否只有十六进制数字

转载 作者:行者123 更新时间:2023-11-30 20:14:24 25 4
gpt4 key购买 nike

我有一个接受 16 位十六进制值作为输入的程序。我想做的就是让它提取这些值。例如,如果我输入:

0xFFFF 0x0000 0x1234

我希望程序迭代此输入字符串,并一次提取每个十六进制值。另外,如果字符串的 0x**** 格式不正确,包含无效字符(例如 $0x5544)或无效的十六进制数字(例如 0x45GG),那么我希望程序打印出“无效输入”。

我目前有一个通过每个字符递增的指针,但我想测试十六进制值以查看它们是否在允许的十六进制数字(0-F)之间,我不知道该怎么做

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <errno.h>

bool isValid1(const char *s){
unsigned long v;
char *endp;
errno = 0;
v = strtoul(s, &endp, 16);
return !*endp && v < 0x10000 && errno != ERANGE;
}

bool isValid2(const char *s){//limited to four HEX characters : 0xXXXX
if(strlen(s)!=6)
return false;
return
*s == '0' && tolower(s[1])=='x' &&
isxdigit(s[2]) && isxdigit(s[3]) && isxdigit(s[4]) && isxdigit(s[5]);
}

int main(void){
char data[] =
"0xFFFF 0x0000 0x1234 0x01234 $0xFFFF 0x45GG 0x12345\n";
char *p = data;
for(p = strtok(p, " \n"); p ; p = strtok(NULL, " \n")){
if(!isValid1(p))
printf("isValid1(%s) : invalid input\n", p);
if(!isValid2(p))
printf("isValid2(%s) : invalid input\n", p);
}
return 0;
}

关于检查 charArray 是否只有十六进制数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26406535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com