Update Bits

Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j)

 Notice

In the function, the numbers N and M will given in decimal, you should also return a decimal number.

Clarification

You can assume that the bits j through i have enough space to fit all of M. That is, if M=10011, you can assume that there are at least 5 bits between jand i. You would not, for example, have j=3 and i=2, because M could not fully fit between bit 3 and bit 2.

Example

Given N=(10000000000)2M=(10101)2i=2j=6

return N=(10001010100)2

分析:http://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/72988

大致步骤如下:

  1. 得到第i位到第j位的比特位为0,而其他位均为1的掩码mask
  2. 使用mask与 N 进行按位与,清零 N 的第i位到第j位。
  3. 对 M 右移i位,将 M 放到 N 中指定的位置。
  4. 返回 N | M 按位或的结果。

获得掩码mask的过程可参考 CTCI 书中的方法,先获得掩码(1111...000...111)的左边部分,然后获得掩码的右半部分,最后左右按位或即为最终结果。

 1 class Solution {
 2 public:
 3     /**
 4      *@param n, m: Two integer
 5      *@param i, j: Two bit positions
 6      *return: An integer
 7      */
 8     int updateBits(int n, int m, int i, int j) {
 9         // write your code here
10         int ones = ~0;
11         int mask = 0;
12         if (j < 31) {
13             int left = ones << (j + 1);
14             int right = ((1 << i) - 1);
15             mask = left | right;
16         } else {
17             mask = (1 << i) - 1;
18         }
19 
20         return (n & mask) | (m << i);
21     }
22 };

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5686916.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AutoSAR(Automotive Open System Architecture)是一种开放式的汽车电子系统架构标准,用于汽车电子控制单元(ECU)软件开发和架构。AutoSAR Update-Bits是AutoSAR架构中用于更新ECU软件的概念。 AutoSAR Update-Bits主要用于在现有的ECU中对软件进行更新和修改。它允许汽车制造商或ECU供应商通过向ECU发送更新数据包来提供新的功能、修复错误或改进现有的软件。这些更新数据包通过AutoSAR Update-Bits的通信机制传输到ECU,并被ECU上的更新管理模块接收和解析。 AutoSAR Update-Bits的更新过程包括以下步骤: 1. 更新数据包准备:汽车制造商或ECU供应商准备包含更新的数据包,并使用AutoSAR的标准规范对其进行打包和编码。 2. 更新数据包传输:更新数据包通过车辆网络,如CAN(Controller Area Network)或FlexRay,传输到目标ECU。 3. 更新管理模块接收:目标ECU上的更新管理模块接收并验证更新数据包的完整性和正确性。 4. 更新数据包解析:更新管理模块将更新数据包解析为可执行代码,并将其存储在ECU的闪存中。 5. 系统重启:ECU完成更新后,它可能需要进行系统重启以使更新生效。 通过使用AutoSAR Update-Bits,汽车制造商和ECU供应商可以在车辆的整个生命周期中对软件进行更新和改进,而无需更换整个ECU。这不仅提供了更灵活和可持续的软件开发和维护方式,还可以显著降低生产成本和减少故障修复时间。 总之,AutoSAR Update-Bits是AutoSAR架构中用于更新ECU软件的机制,它使汽车制造商和ECU供应商能够通过传输和解析更新数据包来增强车辆的功能和安全性,提高软件的可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值