简体   繁体   English

使用按位运算符计算数据类型的最大值和最小值

[英]Computing maximum and minimum value of data type using bitwise operators

I'm starting to learn about the bitwise operators in Java, however, I don't quite catch the questions of computing maximum/minimum value of data types (short, byte, long, float) by using bitwise operators.我开始学习 Java 中的按位运算符,但是,我不太了解使用按位运算符计算数据类型(短、字节、长、浮点)的最大/最小值的问题。

How do we start with that?我们如何开始呢? As I only found problems regarding about finding even/odd number, compute value between pairs.因为我只发现有关查找偶数/奇数的问题,所以计算对之间的值。

Any suggestion will really help as I have spend tremendous hours just by understanding it but I haven't got anywhere so far.任何建议都会真正有帮助,因为我花了很多时间来理解它,但到目前为止我还没有得到任何帮助。 Not many topics about Bitwise Operators Manipulation sadly.可悲的是,关于按位运算符操作的话题并不多。

To get the largest value, fill all the bits to 1. The smallest value is the negation of the largest value.要获得最大值,请将所有位填充为 1。最小值是最大值的否定。

public class Main{
    public static void main(String[] args) {
        int value = 0;
        for(int i=0; i<31; i++) {
           value |= 1<<i;
        }
        System.out.println(value);
        System.out.println(Integer.MAX_VALUE);
        System.out.println(~value);
        System.out.println(Integer.MIN_VALUE);
    }
}

Output Output

2147483647
2147483647
-2147483648
-2147483648

See https://www.vojtechruzicka.com/bit-manipulation-java-bitwise-bit-shift-operations/#:~:text=Java%20uses%20another%20approach%2C%20which%20is%20called%20two%27s,by%20given%20number%20of%20positions%20to%20the%20right .https://www.vojtechruzicka.com/bit-manipulation-java-bitwise-bit-shift-operations/#:~:text=Java%20uses%20another%20approach%2C%20which%20is%20call%20two%27s ,由%20给定%20number%20of%20positions%20to%20the%20right

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM