嗨,
假设我有像“888820c8”这样的字符串。我如何在 C 编程语言中获取 int 中的 3 位?
更新 1 -
这就是我能做的
static const char* getlast(const char *pkthdr)
{
const char *current;
const char *found = NULL;
const char *target = "8888";
int index = 0;
char pcp = 0;
size_t target_length = strlen(target);
current = pkthdr + strlen(pkthdr) - target_length;
while ( current >= pkthdr ) {
if ((found = strstr(current, target))) {
printf("found!\n");
break;
}
current -= 1;
}
if(found)
{
index = found - pkthdr;
index += 4; /*go to last of 8188*/
}
printf("index %d\n", index);
/* Now how to get the next 3 bits*/
printf("pkthdr %c\n", pkthdr[index]);
pcp = pkthdr[index] & 0x7;
printf("%c\n", pcp);
return pcp;
}
显然我知道我的程序的最后一部分是错误的,任何输入都会有帮助。谢谢!
更新2:
感谢普拉蒂克的指点。 下面的代码现在看起来不错吗?
static char getlast(const char *pkthdr)
{
const char *current;
const char *found = NULL;
const char *tpid = "8188";
int index = 0;
char *pcp_byte = 0;
char pcp = 0;
int pcp2 = 0;
char byte[2] = {0};
char *p;
unsigned int uv =0 ;
size_t target_length = strlen(tpid);
current = pkthdr + strlen(pkthdr) - target_length;
//printf("current %d\n", current);
while ( current >= pkthdr ) {
if ((found = strstr(current, tpid))) {
printf("found!\n");
break;
}
current -= 1;
}
found = found + 4;
strncpy(byte,found,2);
byte[2] = '\0';
uv =strtoul(byte,&p,16);
uv = uv & 0xE0;
char i = uv >> 5;
printf("%d i",i);
return i;
}
最佳答案
您拥有的代码可找到包含所需 3 位的字符。该字符将是一个数字('0'
到 '9'
)、一个大写字母('A'
到 'F '
)或小写字母('a'
到 'f'
)。因此第一个任务是将字符转换为其等效的数字,例如像这样
unsigned int value;
if ( sscanf( &pkthdr[index], "%1x", &value ) != 1 )
{
// handle error: the character was not a valid hexadecimal digit
}
此时,您已经有了一个 4 位值,但您想要提取高三位。这可以通过移位和屏蔽来完成,例如
int result = (value >> 1) & 7;
printf( "%d\n", result );
请注意,如果您想从函数中返回 3 位数字,则需要更改函数原型(prototype)以返回 int
,例如
static int getlast(const char *pkthdr)
{
// ...
return result;
}
关于c - 如何从下面提到的字符串格式中获取 '3 bits' 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40471488/