在一个int每四位开关位 [英] Switching bits in each nibble of an int

查看:131
本文介绍了在一个int每四位开关位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何切换仅使用位操作(没有控制结构)整数0级和每个半字节的第3位?我需要什么样的口罩,才能解决这个问题创造?任何帮助将是AP preciated。例如,8(1000)成为1(0001)。

  / *
 * SwitchBits(0)= 0
 * SwitchBits(8)= 1
 * SwitchBits(0x812)= 0x182
 * SwitchBits(为0x12345678)= 0x82a4c6e1
 *合法经营! 〜&安培; ^ | + LT;< >>
 * /
INT SwitchBits(INT N){}


解决方案

code:

 的#include<&stdio.h中GT;
#包括LT&;&inttypes.h GT;静态uint32_t的SwitchBits(uint32_t的N)
{
    uint32_t的bit0_mask = 0x11111111;
    uint32_t的bit3_mask = 0x88888888;
    uint32_t的v_bit0 = N&安培; bit0_mask;
    uint32_t的v_bit3 = N&安培; bit3_mask;
    N'放大器; =〜(bit0_mask | bit3_mask);
    N | =(v_bit0&下; 3;)| (v_bit3>→3);
    返回N;
}INT主要(无效)
{
    uint32_t的i_values​​ [] = {0,8,0x812,0x12345678的,0x9ABCDEF0};
    uint32_t的o_values​​ [] = {0,1,0x182,0x82A4C6E1,0x93B5D7F0};
    枚举{N_VALUES = sizeof的(o_values​​)/的sizeof(o_values​​ [0])};    的for(int i = 0; I< N_VALUES;我++)
    {
        的printf(0X%0.8PRIX32=>为0x%0.8PRIX32(与0X%0.8PRIX32)\\ n
                i_values​​ [I],SwitchBits(i_values​​ [I]),o_values​​ [I]);
    }
    返回0;
}

输出:

  00000000 => 00000000(VS 00000000)
0x00000008 => 00000001(VS 00000001)
0x00000812 => 0x00000182(VS 0x00000182)
为0x12345678 => 0x82A4C6E1(VS 0x82A4C6E1)
0x9ABCDEF0 => 0x93B5D7F0(VS 0x93B5D7F0)

请注意uint32_t的使用,以避免有符号整数与符号位未定义的行为。

How can I switch the 0th and 3rd bits of each nibble in an integer using only bit operations (no control structures)? What kind of masks do I need to create in order to solve this problem? Any help would be appreciated. For example, 8(1000) become 1(0001).

/* 
 * SwitchBits(0) = 0
 * SwitchBits(8) = 1
 * SwitchBits(0x812) = 0x182
 * SwitchBits(0x12345678) = 0x82a4c6e1
 * Legal Operations: ! ~ & ^ | + << >>
 */
int SwitchBits(int n) { 

}

解决方案

Code:

#include <stdio.h>
#include <inttypes.h>

static uint32_t SwitchBits(uint32_t n)
{
    uint32_t bit0_mask = 0x11111111;
    uint32_t bit3_mask = 0x88888888;
    uint32_t v_bit0 = n & bit0_mask;
    uint32_t v_bit3 = n & bit3_mask;
    n &= ~(bit0_mask | bit3_mask);
    n |= (v_bit0 << 3) | (v_bit3 >> 3);
    return n;
}

int main(void)
{
    uint32_t i_values[] = { 0, 8, 0x812, 0x12345678, 0x9ABCDEF0 };
    uint32_t o_values[] = { 0, 1, 0x182, 0x82A4C6E1, 0x93B5D7F0 };
    enum { N_VALUES = sizeof(o_values) / sizeof(o_values[0]) };

    for (int i = 0; i < N_VALUES; i++)
    {
        printf("0x%.8" PRIX32 " => 0x%.8" PRIX32 " (vs 0x%.8" PRIX32 ")\n",
                i_values[i], SwitchBits(i_values[i]), o_values[i]);
    }
    return 0;
}

Output:

0x00000000 => 0x00000000 (vs 0x00000000)
0x00000008 => 0x00000001 (vs 0x00000001)
0x00000812 => 0x00000182 (vs 0x00000182)
0x12345678 => 0x82A4C6E1 (vs 0x82A4C6E1)
0x9ABCDEF0 => 0x93B5D7F0 (vs 0x93B5D7F0)

Note the use of uint32_t to avoid undefined behaviour with sign bits in signed integers.

这篇关于在一个int每四位开关位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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