在 C 中交换整数中的位,你能向我解释这个函数吗? 理解第 3 位和第 5 位交换的简单函数:

如何解决在 C 中交换整数中的位,你能向我解释这个函数吗? 理解第 3 位和第 5 位交换的简单函数:

我想编写一个接收 unsigned char 并在 bit 2bit 4 之间交换并返回新数字的函数。

我不允许使用 if 语句。

所以我在其他函数中找到了这个函数,但这是最容易理解(或尝试理解)的函数。

所有其他函数都涉及到 XOR,老实说我不太明白。

unsigned char SwapBits(unsigned char num)
{
    
    unsigned char mask2 = ( num & 0x04 ) << 2;
    
    unsigned char mask4 = ( num & 0x10 ) >> 2;
    
    unsigned char mask  = mask3 | mask5 ;
    
    return ( num & 0xeb ) | mask;


}    

谁能解释一下这里发生了什么,最重要的是,why? 为什么这里需要 AND,为什么需要 hex address? 为什么我要AND0xeb (255)?我知道这是 char 的范围,但我为什么要这样做。

简而言之, 我知道如何阅读代码。我明白这段代码,但我不明白每一行的用途。

谢谢。

解决方法

首先,通常的约定是位从 0 开始编号,表示最低有效位并向上计数。在本例中,您有一个 8 位值,因此位从右侧的 0 到左侧的 7。

您发布的功能仍然不太正确,但我想我知道您(它)的用途。以下是它正在执行的步骤:

  1. 使用掩码拉出第 2 位(从右数第三个)
  2. 使用掩码拉出第 4 位(从右数第 5 个)
  3. 将第 2 位左移 2 个位置,使其现在位于第 4 位的原始位置
  4. 将第 4 位右移 2 个位置,使其现在位于第 2 位的原始位置
  5. 将这两个位连接成一个值,该值现在交换了第 2 位和第 4 位
  6. 仅屏蔽(使用 & 擦除)原始值的第 2 位和第 4 位
  7. 加入(使用 | 插入)新交换的第 2 位和第 4 位以完成转换

我重新编写了该函数以一次一个地显示每个步骤,以帮助使其更清晰。在您找到的原始函数或其他示例中,您会看到许多这些步骤都发生在同一个语句中。

unsigned char SwapBits(unsigned char num)
{
    // preserve only bit 2
    unsigned char bit2 = num & 0x04;
    
    // preserve only bit 4
    unsigned char bit4 = num & 0x10;
    
    // move bit 2 left to bit 4 position
    unsigned char bit2_moved = bit2 << 2;
    
    // move bit 4 right to bit 2 position
    unsigned char bit4_moved = bit4 >> 2;
    
    // put the two moved bits together into one swapped value
    unsigned char swapped_bits  = bit2_moved | bit4_moved;
    
    // clear bits 2 and 4 from the original value
    unsigned char num_with_swapped_bits_cleared = num & ~0x14;
    
    // put swapped bits back into the original value to complete the swap
    return num_with_swapped_bits_cleared | swapped_bits;
} 

倒数第二个步骤 num & ~0x14 可能需要一些解释。由于我们要保存除第 2 位和第 4 位之外的所有原始位,因此我们仅屏蔽(擦除)我们正在更改的位,而保留所有其他位。我们要擦除的位位于位置 2 和 4,它们是掩码 0x14 中的 1。所以我们在 0x14 上做一个补码 (~) 把它变成除了第 2 位和第 4 位中的 0 之外的所有地方都为 1。然后我们将该值与原始数字进行 AND 运算,这具有将第 2 位和第 4 位变为 0 而离开的效果所有其他人独自一人。这允许我们在新的交换位中进行 OR 运算,作为完成该过程的最后一步。

,

您必须阅读binary representation of number

unsigned char SwapBits(unsigned char num)
{
// let say that [num] = 46,it means that is is represented 0b00101110

    unsigned char mask2 = ( num & 0x04 ) << 2;
// now,another byte named mask2 will be equal to:
// 0b00101110 num
// 0b00000100 0x04
//     . .1.  mask2 = 4. Here the & failed with . as BOTH ([and]) bits need to be set. Basically it keeps only numbers that have the 3rd bit set

    unsigned char mask4 = ( num & 0x10 ) >> 2;
// 0b00101110 num
// 0b00010000 0x10 -> means 16 in decimal or 0b10000 in binary or 2^4 (the power is also the number of trailing 0 after the bit set)
// 0b00.....0 mask4 = 0,all bits failed to be both set

    unsigned char mask  = mask3 | mask5 ;
// mask will take bits at each position if either set by mask3 [or] mask5 so:
// 0b1001 mask3
// 0boo11 mask4
// 0b1011 mask

    return ( num & 0xeb ) | mask; // you now know how it works ;) solve this one. PS: operation between Brackets have priority
}    

如果您有兴趣了解按位运算符的基础知识,可以查看 this introduction

建立信心后,您可以尝试 solving algorithms using only bitwise operators,,您将探索更深入的按位运算并查看其对运行时的影响;)

我还推荐阅读Bit Twiddling Hacks,老歌但好歌!

b = ((b * 0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL >> 32; // reverse your byte!

理解第 3 位和第 5 位交换的简单函数:

如果要交换位索引 3 和位索引 5,则必须执行以下操作:

int n = 0b100010
int mask = 0b100000 // keep bit index 5 (starting from index 0)
int mask2 = 0b1000 // keep bit index 3

n = (n & mask) >> 2 | (n & mask2) << 2 | (n & 0b010111); 

// (n & mask) >> 2
// the mask index 5 is decrease by 2 position (>>2) and brings along with it the bit located at index 5 that it had captured in n thanks to the AND operand. 

// | (n & mask2) << 2
// mask2 is increased by 2 index and set it to 0 since n didn't have a bit set at index 3 originally.

// | (n & 0b010111); // bits 0 1 2 and 4 are preserved
// since we assign the value to n all other bits would have been wiped out if we hadn't kept their original value thanks to the mask on which we do not perform any shift operations.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-