且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与在C ++中,前导零十六进制数变化位(C)

更新时间:2023-11-08 11:48:28

在一个24位数位#7(从左至右,因为你在你的例子一样,而不是从正确的,因为以往那样)是总是要在从左侧的第二个字节。你能解决你的问题,而采取的第二个十六进制数字,将其转换为数字0..15,并设置其位#3(左重新计数),并将结果转换回一个十六进制整个数字转换为整数数字。

In a 24-bit number bit #7 (counting from the left, as you did in your example, not from the right, as is done conventionally) is always going to be in the second byte from the left. You can solve your problem without converting the entire number to integer by taking that second hex digit, converting it to a number 0..15, setting its bit #3 (again counting from the left), and converting the result back to a hex digit.

int fromHex(char c) {
    c = toupper(c);
    if (c >= '0' && c <= '9') {
        return c-'0';
    } else {
        return c-'A'+10;
    }
}
char toHexDigit(int n) {
    return n < 10 ? '0'+n : 'A'+n-10;
}

char myNum[] = "002A05";
myNum[1] = toHexDigit(fromHex(myNum[1]) | 2);
printf("%s\n", myNum);

这版画022A05(链接ideone )。

This prints '022A05' (link to ideone).