与在C ++中,前导零十六进制数变化位(C) [英] Change bit of hex number with leading zeros in C++,(C)

查看:159
本文介绍了与在C ++中,前导零十六进制数变化位(C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个号码在十六进制字符串:

I have this number in hex string:

002A05.

我要这个号码的7个位为1,所以转换后我将获得

I need to set 7-th bit of this number to 1, so after conversion I will get

022A05

但是它具有与每6个字符的十六进制数来工作。

But it has to work with every 6 chars hex number.

我试图通过strtol将十六进制字符串转换为整数,但此功能带前导零。

I tried converting hex string to integer via strtol, but that function strip leading zeros.

请帮助我,我怎么能解决这个问题。

Please help me how can I solve it.

推荐答案

在一个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).

这篇关于与在C ++中,前导零十六进制数变化位(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆