Java位运算案例如何编写

wen java案例 27

本文目录导读:

Java位运算案例如何编写

  1. 基础位运算符示例
  2. 移位运算符案例
  3. 实用案例:权限系统
  4. 实用案例:颜色处理
  5. 算法案例:判断奇偶和交换数值
  6. 符号位操作案例
  7. 位图(Bitmap)应用案例
  8. 运行建议

我来为您提供几个Java位运算的经典案例,从基础到实战应用。

基础位运算符示例

public class BitwiseBasicExample {
    public static void main(String[] args) {
        int a = 60;  // 二进制: 0011 1100
        int b = 13;  // 二进制: 0000 1101
        System.out.println("a = " + a + " (" + toBinaryString(a, 8) + ")");
        System.out.println("b = " + b + " (" + toBinaryString(b, 8) + ")");
        System.out.println();
        // 位与 (&)
        System.out.println("a & b = " + (a & b) + " (" + toBinaryString(a & b, 8) + ")");
        // 位或 (|)
        System.out.println("a | b = " + (a | b) + " (" + toBinaryString(a | b, 8) + ")");
        // 位异或 (^)
        System.out.println("a ^ b = " + (a ^ b) + " (" + toBinaryString(a ^ b, 8) + ")");
        // 位非 (~)
        System.out.println("~a = " + (~a) + " (" + toBinaryString(~a, 32) + ")");
    }
    // 辅助方法:格式化二进制字符串
    private static String toBinaryString(int num, int bits) {
        String binary = Integer.toBinaryString(num);
        if (bits <= 32) {
            // 补零
            while (binary.length() < bits) {
                binary = "0" + binary;
            }
            // 如果太长,截取
            if (binary.length() > bits) {
                binary = binary.substring(binary.length() - bits);
            }
        }
        return binary;
    }
}

移位运算符案例

public class ShiftExample {
    public static void main(String[] args) {
        int num = 8;  // 二进制: 0000 1000
        System.out.println("原始值: " + num + " (" + toBinaryString(num, 8) + ")");
        System.out.println();
        // 左移 (<<)
        System.out.println(num + " << 1 = " + (num << 1) + " (乘2)");
        System.out.println(num + " << 2 = " + (num << 2) + " (乘4)");
        System.out.println(num + " << 3 = " + (num << 3) + " (乘8)");
        System.out.println();
        // 右移 (>>)
        System.out.println(num + " >> 1 = " + (num >> 1) + " (除2)");
        System.out.println(num + " >> 2 = " + (num >> 2) + " (除4)");
        System.out.println(num + " >> 3 = " + (num >> 3) + " (除8)");
        System.out.println();
        // 无符号右移 (>>>)
        int negative = -8;
        System.out.println("负数无符号右移:");
        System.out.println(negative + " >>> 1 = " + (negative >>> 1));
        System.out.println(negative + " >>> 2 = " + (negative >>> 2));
    }
    private static String toBinaryString(int num, int bits) {
        String binary = Integer.toBinaryString(num);
        while (binary.length() < bits) {
            binary = "0" + binary;
        }
        if (binary.length() > bits) {
            binary = binary.substring(binary.length() - bits);
        }
        return binary;
    }
}

实用案例:权限系统

public class PermissionExample {
    // 权限位定义
    public static final int READ    = 1 << 0;  // 0001 = 1
    public static final int WRITE   = 1 << 1;  // 0010 = 2
    public static final int EXECUTE = 1 << 2;  // 0100 = 4
    public static final int DELETE  = 1 << 3;  // 1000 = 8
    public static void main(String[] args) {
        int userPermissions = 0;
        // 添加权限
        userPermissions = addPermission(userPermissions, READ);
        userPermissions = addPermission(userPermissions, WRITE);
        userPermissions = addPermission(userPermissions, EXECUTE);
        System.out.println("用户权限: " + toBinaryString(userPermissions, 4));
        System.out.println("权限值: " + userPermissions);
        System.out.println();
        // 检查权限
        System.out.println("有读取权限? " + hasPermission(userPermissions, READ));
        System.out.println("有删除权限? " + hasPermission(userPermissions, DELETE));
        System.out.println();
        // 移除权限
        userPermissions = removePermission(userPermissions, WRITE);
        System.out.println("移除写权限后: " + toBinaryString(userPermissions, 4));
        System.out.println("有写权限? " + hasPermission(userPermissions, WRITE));
    }
    // 添加权限
    public static int addPermission(int permissions, int permission) {
        return permissions | permission;
    }
    // 移除权限
    public static int removePermission(int permissions, int permission) {
        return permissions & ~permission;
    }
    // 检查权限
    public static boolean hasPermission(int permissions, int permission) {
        return (permissions & permission) == permission;
    }
    private static String toBinaryString(int num, int bits) {
        String binary = Integer.toBinaryString(num);
        while (binary.length() < bits) {
            binary = "0" + binary;
        }
        return binary;
    }
}

实用案例:颜色处理

public class ColorExample {
    public static void main(String[] args) {
        // 创建颜色 (使用ARGB格式,但这里使用RGB)
        int color = createColor(255, 128, 64);  // 橙色
        System.out.println("颜色值: " + Integer.toHexString(color));
        System.out.println();
        // 提取颜色分量
        int red = getRed(color);
        int green = getGreen(color);
        int blue = getBlue(color);
        System.out.println("红色分量: " + red);
        System.out.println("绿色分量: " + green);
        System.out.println("蓝色分量: " + blue);
        System.out.println();
        // 修改颜色分量
        int newColor = setRed(color, 100);
        System.out.println("修改红色后: R=" + getRed(newColor) + 
                          ", G=" + getGreen(newColor) + 
                          ", B=" + getBlue(newColor));
    }
    // 创建颜色 (RGB格式)
    public static int createColor(int r, int g, int b) {
        return (r << 16) | (g << 8) | b;
    }
    // 获取红色分量
    public static int getRed(int color) {
        return (color >> 16) & 0xFF;
    }
    // 获取绿色分量
    public static int getGreen(int color) {
        return (color >> 8) & 0xFF;
    }
    // 获取蓝色分量
    public static int getBlue(int color) {
        return color & 0xFF;
    }
    // 设置红色分量
    public static int setRed(int color, int newRed) {
        return (color & 0x00FFFF) | (newRed << 16);
    }
}

算法案例:判断奇偶和交换数值

public class AlgorithmExample {
    public static void main(String[] args) {
        // 1. 判断奇偶
        int[] numbers = {2, 3, 4, 5, 7, 10};
        System.out.println("判断奇偶数:");
        for (int num : numbers) {
            System.out.println(num + " 是" + (isEven(num) ? "偶数" : "奇数"));
        }
        System.out.println();
        // 2. 交换两个数
        int a = 10, b = 20;
        System.out.println("交换前: a=" + a + ", b=" + b);
        swap(a, b);
        System.out.println("交换后: a=" + a + ", b=" + b);
        System.out.println("注意:上面的交换其实不会生效,因为Java是值传递");
        // 使用数组实现交换
        int[] arr = {10, 20};
        System.out.println("交换前: " + arr[0] + ", " + arr[1]);
        swapArray(arr);
        System.out.println("交换后: " + arr[0] + ", " + arr[1]);
        System.out.println();
        // 3. 判断是否是2的幂
        int[] powers = {0, 1, 2, 3, 4, 8, 16, 32, 63, 64};
        System.out.println("判断2的幂:");
        for (int num : powers) {
            System.out.println(num + " 是2的幂? " + isPowerOfTwo(num));
        }
    }
    // 判断偶数
    public static boolean isEven(int num) {
        return (num & 1) == 0;
    }
    // 交换两个整数(使用位运算)
    public static void swap(int a, int b) {
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        System.out.println("方法内: a=" + a + ", b=" + b);
    }
    // 使用数组实现交换
    public static void swapArray(int[] arr) {
        if (arr.length >= 2) {
            arr[0] = arr[0] ^ arr[1];
            arr[1] = arr[0] ^ arr[1];
            arr[0] = arr[0] ^ arr[1];
        }
    }
    // 判断是否是2的幂
    public static boolean isPowerOfTwo(int num) {
        return num > 0 && (num & (num - 1)) == 0;
    }
}

符号位操作案例

public class SignBitExample {
    public static void main(String[] args) {
        System.out.println("正数符号位:");
        int positive = 42;
        System.out.println(positive + " 的符号位: " + getSignBit(positive));
        System.out.println(positive + " 是正数? " + isPositive(positive));
        System.out.println();
        System.out.println("负数符号位:");
        int negative = -42;
        System.out.println(negative + " 的符号位: " + getSignBit(negative));
        System.out.println(negative + " 是正数? " + isPositive(negative));
        System.out.println();
        // 取绝对值(不使用Math.abs)
        System.out.println("取绝对值:");
        System.out.println(negative + " 的绝对值: " + absolute(negative));
        System.out.println(positive + " 的绝对值: " + absolute(positive));
    }
    // 获取符号位
    public static int getSignBit(int num) {
        return num >> 31;
    }
    // 判断是否是正数
    public static boolean isPositive(int num) {
        return (num >> 31) == 0;
    }
    // 取绝对值
    public static int absolute(int num) {
        int mask = num >> 31;
        return (num + mask) ^ mask;
    }
}

位图(Bitmap)应用案例

public class BitSetExample {
    public static void main(String[] args) {
        // 假设我们要存储0-7的数字集合
        byte bitSet = 0;
        // 添加元素
        bitSet = setBit(bitSet, 2);
        bitSet = setBit(bitSet, 5);
        System.out.println("位图值: " + toBinaryString(bitSet, 8));
        System.out.println("包含2? " + testBit(bitSet, 2));
        System.out.println("包含3? " + testBit(bitSet, 3));
        System.out.println("包含5? " + testBit(bitSet, 5));
        System.out.println();
        // 遍历所有元素
        System.out.println("集合中的元素:");
        for (int i = 0; i < 8; i++) {
            if (testBit(bitSet, i)) {
                System.out.print(i + " ");
            }
        }
    }
    // 设置指定位置的位为1
    public static byte setBit(byte bits, int position) {
        return (byte)(bits | (1 << position));
    }
    // 清除指定位置的位
    public static byte clearBit(byte bits, int position) {
        return (byte)(bits & ~(1 << position));
    }
    // 测试指定位置的位是否为1
    public static boolean testBit(byte bits, int position) {
        return (bits & (1 << position)) != 0;
    }
    private static String toBinaryString(int num, int bits) {
        StringBuilder sb = new StringBuilder();
        for (int i = bits - 1; i >= 0; i--) {
            sb.append((num >> i) & 1);
        }
        return sb.toString();
    }
}

运行建议

  1. 可以单独运行每个案例文件
  2. 建议使用IDE(如IntelliJ IDEA或Eclipse)运行
  3. 运行前确保文件中有正确的main方法
  4. 可以修改参数值测试不同情况

这些案例涵盖了Java位运算的常见应用场景,通过实际编码可以更好地理解位运算的原理和优势。

抱歉,评论功能暂时关闭!