Bit Manipulation

本文详细介绍了如何找到一个整数的下一位最小和最大整数,这些整数在二进制表示中具有相同的1位数量。通过从右到左遍历整数,我们能够有效地增加或减少其值,同时保持相同数量的1位。此外,文章还提供了一个用于交换整数奇偶位的C代码示例,并讨论了在只使用获取第j位的A[i]操作的情况下,如何在O(n)时间内找到丢失的整数。

From: career up 150.

1. Question:

Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation.

Answer:

Number Properties Approach for Next Number
Observations:
»»If we “turn on” a 0, we need to “turn off” a 1
»»If we turn on a 0 at bit i and turn off a 1 at bit j, the number changes by 2^i - 2^j.
»»If we want to get a bigger number with the same number of 1s and 0s, i must be bigger than j.


Solution:
1. Traverse from right to left. Once we’ve passed a 1, turn on the next 0. We’ve now increased the number by 2^i. Yikes! Example: xxxxx011100 becomes xxxxx111100
2. Turn off the one that’s just to the right side of that. We’re now bigger by 2^i - 2^(i-1) Example: xxxxx111100 becomes xxxxx101100
3. Make the number as small as possible by rearranging all the 1s to be as far right as possible: Example: xxxxx101100 becomes xxxxx100011


To get the previous number, we do the reverse.
1. Traverse from right to left. Once we’ve passed a zero, turn off the next 1. Example: xxxxx100011 becomes xxxxx000011.
2. Turn on the 0 that is directly to the right. Example: xxxxx000011 becomes xxxxx010011.
3. Make the number as big as possible by shifting all the ones as far to the left as possible. Example: xxxxx010011 becomes xxxxx011100 .


2. Question:

Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc).

>> cat swap.c 
#include <stdio.h>

unsigned int swap(unsigned int i)
{
        return (((i & 0xaaaaaaaa) >> 1) | ((i & 0x55555555) << 1));
}

int main()
{
        unsigned int i = 10;
        printf("%d\n", swap(i));
}

3. From CLRS

Problems 4-2: Finding the missing integer
An array A[1 n] contains all the integers from 0 to n except one. It would be easy to determine the missing integer in O(n) time by using an auxiliary array B[0 n] to record which numbers appear in A. In this problem, however, we cannot access an entire integer in A with a single operation. The elements of A are represented in binary, and the only operation we can use to access them is "fetch the jth bit of A[i]," which takes constant time.  Show that if we use only this operation, we can still determine the missing integer in O(n) time.

Answer:

http://www.cs.nyu.edu/courses/summer08/G22.1170-001/hw02-soln.pdf

http://stackoverflow.com/questions/5374539/report-all-missing-numbers-in-an-array-of-integers-represented-in-binary

http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-about-algorithms-bit-magic

Say all numbers are represented by k bits and set j as the least significant bit (initially the rightmost).
1. Starting from j, separate all the numbers in L into two sets (S1 containing all numbers that have 1 as its jth bit, and S2 containing all numbers that have 0 in that position).
2. The smaller of the two sets contains the missing number, recurse on this subset and set j = j-1

<think> 我们正在处理用户关于"bitbitaction"的查询。用户希望了解这两个概念的相关介绍。 根据之前的对话历史,用户已经询问过"bitaction和bool区别",并得到了详细解答。现在用户进一步询问"bitbitaction的相关介绍"。 需要注意的是,在之前的回答中,我们解释了BitAction通常指位操作(如SET/CLEAR/TOGGLE),而Bit是二进制位(0或1)。 然而,直接搜索"bitaction"可能不会得到太多结果,因为它可能不是一个广泛使用的标准术语。根据上下文,它可能是指位操作(bit manipulation)或特定领域(如硬件描述语言)中的概念。 因此,搜索策略如下: 1. 搜索"bit"(位)的基础概念,因为这是计算机科学的基本单位。 2. 搜索"bitaction"的含义,但考虑到它可能是一个特定术语,我们可能需要结合上下文(如之前的对话中提到的嵌入式系统或硬件控制)来理解。 经过分析,在之前的回答中,我们将BitAction解释为一种位操作模式(如SET, CLEAR, TOGGLE等)。因此,我们可以将BitAction理解为位操作(bit manipulation)的一种具体形式或模式。 现在,我们进行网络搜索: 搜索词1: "what is a bit in computer science" 搜索词2: "bitaction meaning" (如果结果少,则尝试 "bit action in programming", "bit manipulation actions") 假设我们从搜索中获取以下信息: 关于Bit(位): - 位是计算机存储信息的最小单位,表示二进制数字,值为0或1。 - 8位组成1字节。 - 位用于表示数字、字符、图像等所有数据。 关于BitAction(位操作): - 在硬件描述语言(如VHDL)中,有对信号(位)的操作,如赋值、翻转等。 - 在嵌入式C/C++中,位操作通常通过宏或内联函数实现,例如: #define SET_BIT(reg, bit) ((reg) |= (1 << (bit))) #define CLEAR_BIT(reg, bit) ((reg) &= ~(1 << (bit))) #define TOGGLE_BIT(reg, bit) ((reg) ^= (1 << (bit))) - 在Verilog中,位操作包括设置、清除和翻转等。 因此,我们可以将回答组织为两个部分:Bit的介绍和BitAction(位操作)的介绍。 回答结构: 1. Bit(位)的介绍 - 定义 - 重要性 - 应用 2. BitAction(位操作)的介绍 - 定义(作为对位进行操作的模式) - 常见操作(SET, CLEAR, TOGGLE等) - 应用场景(硬件控制、优化等) 注意:由于用户要求将答案组织为多个方法或步骤(每个步骤间换行),我们可以将这两个部分视为两个步骤,但更准确的是两个主题。 同时,用户要求避免使用步骤词汇,因此我们直接分主题描述。 此外,如果涉及代码,按照格式要求给出。 最后,生成相关问题。 具体回答如下: </think> ### Bit(位)与 BitAction(位操作)介绍 #### Bit(二进制位) Bit 是计算机存储信息的最小单位,取值为 0 或 1,用于表示二进制状态。其核心特性: - **物理基础**:晶体管通/断状态在硬件层的实现 - **数据表示**:$n$ 位可表示 $2^n$ 种状态(如 8 位 = 256 种值) - **内存映射**:内存按字节(8 位)寻址,单比特需通过位运算访问 ```c // C 语言中的位定义(寄存器操作) #define FLAG_REGISTER 0x20 // 00100000 二进制 uint8_t status_register = 0; ``` #### BitAction(位操作) BitAction 指对特定比特位的控制指令集,常见于嵌入式开发和硬件描述语言: - **核心操作类型** - `SET`:置位(1 → 1 或 0 → 1) - `CLEAR`:清零(1 → 0) - `TOGGLE`:翻转(0 ↔ 1) - `READ`:读取状态 ```vhdl -- VHDL 位操作实例 signal control_bit : std_logic := '0'; control_bit <= '1'; -- SET 操作 control_bit <= not control_bit; -- TOGGLE 操作 ``` - **硬件级优化** - 直接操控寄存器特定位(如 ARM Cortex-M 的 GPIO 控制) - 功耗优化公式:$$P_{saved} = \sum_{i=0}^{n} (V_{dd}^2 \cdot f \cdot C_i \cdot \Delta bit_i)$$ - 内存效率:8 个标志位仅需 1 字节(布尔数组需 8 字节) #### 典型应用场景 **嵌入式系统(C 语言)** ```c // STM32 单片机 LED 控制 #define LED_PIN 5 GPIOB->ODR |= (1 << LED_PIN); // SET:PB5 置高电平 GPIOB->ODR &= ~(1 << LED_PIN); // CLEAR:PB5 置低电平 ``` **数字电路设计(Verilog)** ```verilog // 时钟分频器位翻转 always @(posedge clk) begin div_counter <= div_counter + 1; if (div_counter == 8'hFF) output_signal <= ~output_signal; // TOGGLE end ``` #### 关键差异总结 | **维度** | Bit | BitAction | |---------------|--------------------------------------|--------------------------------| | **本质** | 数据存储单元 | 比特控制指令集 | | **操作目标** | 单个二进制值(0/1) | 寄存器/内存中的特定位 | | **典型场景** | 数据编码、数值存储 | 硬件寄存器控制、状态标志管理 | | **优化方向** | 存储密度(如位字段) | 实时性与功耗控制 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值