我有字符value = "ab"
,如何转换它以获得以下位掩码int mask = 0xab
?有没有可能做int mask = 0x(value)
或类似的东西。
'ab'
是一个多字符常量。它究竟做什么是实现定义的,所以它不会在不同的编译器上给你相同的结果。不能保证结果在任何方面都是有意义的。你可能想要的是这个:
const unsigned char *a = "ab";
现在它是一个字符串文字,你获取它的地址,并将其分配给一个指针。您可以像这样进行拆分:
char b = a[0];
char c = a[1];
我想
你想要这个:
从您的评论中,从COM端口读取的3个字符0 1 b8
应转换为数字0x1b8
。
让我们假设:
int c1 = 0;
int c2 = 0x1;
int c3 = 0xb8;
那么你想要的数字可以像这样得到:
int numberyouwant = (c1 << 16) | (c2 << 8) | c3;
你可能想要这个:
#include <stdio.h>
#include <string.h>
int main() {
char buffer[] = "ab" ;
int x = strtol(buffer, NULL, 16);
printf("x in hexadecimal = %xnx in decimal = %dn", x, x);
return 0;
}
或者稍微复杂一点,如果你只想在字符串中间选择 2 个字符:
#include <stdio.h>
#include <string.h>
int main() {
char buffer[] = "ab12345" ;
char tempbuffer[3];
tempbuffer[0] = buffer[0];
tempbuffer[1] = buffer[1];
tempbuffer[2] = 0;
int x = strtol(tempbuffer, NULL, 16);
printf("x in hexadecimal = %xnx in decimal = %dn", x, x);
return 0;
}