zoukankan      html  css  js  c++  java
  • [JAVA&C]移位操作的不同

    如题,对于c来说<< 和 >> 是针对无符号整数,高位低位都是自动补0;而对java来说模糊了这个概念,Java如果直接>>右移,他的符号位不变,左边补上符号位,即正数补零,负数补1。只有>>>才是全部补0的,而对于左移都是低位补0,没有区别。

    参考:java移位运算符:<<(左移)、>>(带符号右移)和>>>(无符号右移)。


    这点在leetcode这题上特别明显:

    Reverse Bits

    Reverse bits of a given 32 bits unsigned integer.

    java
    public
    class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { n = (n >>> 16) | (n << 16);//切半交换 n = ((n & 0xff00ff00) >>> 8) | ((n & 0x00ff00ff) << 8);//1/4切半交换 n = ((n & 0xf0f0f0f0) >>> 4) | ((n & 0x0f0f0f0f) << 4);//1/8切半交换 n = ((n & 0xcccccccc) >>> 2) | ((n & 0x33333333) << 2);//1100&0011 n = ((n & 0xaaaaaaaa) >>> 1) | ((n & 0x55555555) << 1);//1010&0101 return n; } }
    c
    class Solution {
    public:
        uint32_t reverseBits(uint32_t n) {
            n = (n >> 16) | (n << 16);//切半交换
            n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);//1/4切半交换
            n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);//1/8切半交换
            n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);//1100&0011
            n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);//1010&0101
            return n;
        }
    };
    原创供学习参考使用,转载请注明出处http://www.cnblogs.com/cuphoria/ @jm_epiphany
  • 相关阅读:
    L1-009. N个数求和
    L1-008. 求整数段和
    L1-007. 念数字
    L1-006. 连续因子
    L1-005. 考试座位号
    L1-003. 个位数统计
    mtk preloader学习笔记
    android kernel启动学习笔记
    android MTK平台编译UBOOT学习笔记
    dota2输入法无候选框?
  • 原文地址:https://www.cnblogs.com/cuphoria/p/10692504.html
Copyright © 2011-2022 走看看