java𞓜、&、>、

7939 ワード

package aa;

public class BitUtils {
          
        /** 
         *            
* : 0000 1011 0 1, 2 0
* *
@param source * * @param pos * (0<=pos<=7) * @return (0 or 1) */ public static byte getBitValue(byte source, int pos) { return (byte) ((source >> pos) & 1); } /** *
* : 0000 1011 0000 1111, 2 1
* *
@param source * * @param pos * (0<=pos<=7) * @param value * 0, 1, 0 1 , 0 0 * * @return */ public static byte setBitValue(byte source, int pos, byte value) { byte mask = (byte) (1 << pos); if (value > 0) { source |= mask; } else { source &= (~mask); } return source; } /** *
* : 0000 1011 3 , 0000 0011; 2 , 0000 1111
* *
@param source * * @param pos * (0<=pos<=7) * * @return */ public static byte reverseBitValue(byte source, int pos) { byte mask = (byte) (1 << pos); return (byte) (source ^ mask); } /** * 1
* *
@param source 00001011 * * @param pos * (0<=pos<=7) * @return true 1, false 0 */ public static boolean checkBitValue(byte source, int pos) { source = (byte) (source >>> pos); return (source & 1) == 1; } /** *
* *
@param args */ public static void main(String[] args) { // 11 ( 0000 1011) byte source = 11; // 2 , 0000 1011 for (byte i = 7; i >= 0; i--) { System.out.printf("%d ", getBitValue(source, i)); } // 6 1 , 75 (0100 1011) System.out.println("
" + setBitValue(source, 6, (byte) 1)); // 6 , 75(0100 1011) System.out.println(reverseBitValue(source, 6)); // 6 1, false System.out.println(checkBitValue(source, 6)); // 1 , 0 1 3 for (byte i = 0; i < 8; i++) { if (checkBitValue(source, i)) { System.out.printf("%d ", i); } } } }
 
転載先:https://www.cnblogs.com/wangchaoyu/p/8865696.html