2022/01/16 位运算

本文介绍了多种位操作的实现方法及应用场景,包括判断一个数是否为2的幂、4的幂,计算位1的个数,交换两个数字,找出数组中只出现一次的数字等。此外还介绍了如何计算两个数的汉明距离、判断一个数的二进制位是否交替变化、计算子集的异或总和等实用技巧。

1. 231. 2 的幂

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return n > 0 && (n & -n) == n;
    }
};

2. 342. 4的幂

class Solution {
public:
    bool isPowerOfFour(int n) {
        return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0;
    }
};

3. 191. 位1的个数

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ret = 0;
        while (n) {
            n &= n - 1;
            ret++;
        }
        return ret;
    }
};

4. 面试题 16.01. 交换数字

class Solution {
public:
    vector<int> swapNumbers(vector<int>& numbers) {
        numbers[0] ^= numbers[1];
        numbers[1] ^= numbers[0];
        numbers[0] ^= numbers[1];
        return numbers;
    }
};

5. 136. 只出现一次的数字

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ret = 0;
        for (auto e: nums) ret ^= e;
        return ret;
    }
};

6. 461. 汉明距离

class Solution {
public:
    int hammingDistance(int x, int y) {
        int s = x ^ y, ret = 0;
        while (s) {
            s &= s - 1;
            ret++;
        }
        return ret;
    }
};

7. 693. 交替位二进制数

class Solution {
public:
    bool hasAlternatingBits(int n) {
        while(n>0){
            if(n%2==(n/2)%2)return false;n/=2;
        }
        return true;
    }
};

8. 1863. 找出所有子集的异或总和再求和

class Solution {
public:
    int subsetXORSum(vector<int>& nums) {
        int res = 0;
        int n = nums.size();
        for (auto num: nums){
            res |= num;
        }
        return res << (n - 1);
    }
};

9. 371. 两整数之和

class Solution {
public:
    int getSum(int a, int b) {
        while (b != 0) {
            unsigned int carry = (unsigned int)(a & b) << 1;
            a = a ^ b;
            b = carry;
        }
        return a;
    }
};

10. 面试题 05.01. 插入

class Solution {
public:
    int insertBits(int N, int M, int i, int j) {
        return(N>>j>>1<<j<<1)|(M<<i)|(N&((1<<i)-1));
    }
};

 

### CalculateCRC16方法的功能 CRC16(Cyclic Redundancy Check 16-bit)即16位循环冗余校验,是一种数据传输检错功能,用于检测数据在传输过程中是否发生错误。在C#中,`CalculateCRC16`方法的主要功能是对输入的数据进行CRC16计算,生成一个16位的校验值。该校验值会附加在数据后面一起传输,接收方在接收到数据后,会重新计算CRC16值并与接收到的校验值进行比较,如果两者相同,则认为数据在传输过程中没有发生错误;如果不同,则说明数据可能已经损坏。 以下是一个简单的`CalculateCRC16`方法示例: ```csharp public static ushort CalculateCRC16(byte[] data) { ushort crc = 0xFFFF; for (int i = 0; i < data.Length; i++) { crc ^= (ushort)(data[i] << 8); for (int j = 0; j < 8; j++) { if ((crc & 0x8000) != 0) { crc = (ushort)((crc << 1) ^ 0x1021); } else { crc <<= 1; } } } return crc; } ``` ### 优化`CalculateCRC16`方法以提高效率 可以通过使用预计算的CRC16表来优化`CalculateCRC16`方法,减少每次计算时的循环次数,从而提高计算效率。以下是优化后的代码示例: ```csharp public static class Crc16 { private static readonly ushort[] CrcTable = new ushort[256]; static Crc16() { for (ushort i = 0; i < CrcTable.Length; ++i) { ushort value = 0; ushort temp = i; for (byte j = 0; j < 8; ++j) { if ((((value ^ temp) & 0x0001) != 0)) { value = (ushort)((value >> 1) ^ 0x8408); } else { value >>= 1; } temp >>= 1; } CrcTable[i] = value; } } public static ushort Calculate(byte[] data) { ushort crc = 0xFFFF; for (int i = 0; i < data.Length; i++) { byte index = (byte)(crc ^ data[i]); crc = (ushort)((crc >> 8) ^ CrcTable[index]); } return crc; } } ``` ### 在VS2022 C#上位机串口升级MCU场景中的应用 在VS2022 C#上位机通过串口发送新固件升级MCU的场景中,`CalculateCRC16`方法可以用于保证数据传输的完整性。具体应用如下: - **发送数据时添加CRC校验值**:在上位机发送固件数据包之前,先计算数据包的CRC16校验值,然后将校验值附加在数据包后面一起发送给MCU。 ```csharp // 假设data是要发送的固件数据包 byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 }; ushort crc = Crc16.Calculate(data); byte[] crcBytes = BitConverter.GetBytes(crc); byte[] dataWithCrc = new byte[data.Length + crcBytes.Length]; Array.Copy(data, dataWithCrc, data.Length); Array.Copy(crcBytes, 0, dataWithCrc, data.Length, crcBytes.Length); // 发送dataWithCrc到串口 ``` - **接收数据时验证CRC校验值**:MCU在接收到数据包后,重新计算接收到的数据(不包括校验值)的CRC16校验值,并与接收到的校验值进行比较。如果两者相同,则认为数据传输正确;如果不同,则要求上位机重新发送数据。 ```csharp // 假设receivedData是接收到的包含CRC校验值的数据包 byte[] receivedData = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x12, 0x34 }; byte[] data = new byte[receivedData.Length - 2]; Array.Copy(receivedData, data, data.Length); ushort receivedCrc = BitConverter.ToUInt16(receivedData, receivedData.Length - 2); ushort calculatedCrc = Crc16.Calculate(data); if (receivedCrc == calculatedCrc) { // 数据传输正确,继续处理 } else { // 数据传输错误,要求重新发送 } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值