zoukankan      html  css  js  c++  java
  • Chp5: Bit Manipulation

    Bits Facts and Tricks

    x ^ 0s =  x

    x & 0s =  0

    x | 0s = x

    x ^ 1s = ~x

    x & 1s = x

    x | 1s = 1s

    x ^ x = 0

    x & x = x

    x | x = x

    Common Bit Tasks:  Get, Set, Clear And Update

    Get:  num & (1 << i) != 0

    Set: num | (1 << i)

    Clear:

    clear ith bit: num & (~(1 << i))

    clear all bits from the most significant bit through i: num & ((1 << i) - 1)

    clear all bits from i though 0: num & (~((1 << (i + 1)) - 1))

    Update: (num & (~(1 << i))) | (v << i)

    5.4 

    1 ((n & (n - 1)) == 0) //check if n is a power of 2 (or if n is 0)

    5.5 Swap odd and even bits in an integer with as few instructions ad possible.

    1 //0xaaaaaa is 1010101010 which mask all odd bits
    2 public int swapOddEven(int x){
    3     return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) );
    4 }
  • 相关阅读:
    网页CSS2
    C#(1)—类型、常量及变量
    进制转化
    12月26日提纲
    12月24日笔记
    12月23日笔记
    12月22日笔记
    12月21日笔记
    12月20日笔记
    break、continue与数组
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3464612.html
Copyright © 2011-2022 走看看