简体   繁体   English

有人可以向我解释这个按位程序吗?

[英]Can someone please explain this bitwise program to me?

public class UpCase {
    public static void main(String[] args) {
        int t;
        byte val;
        val = 123;
        for (t = 128; t > 0; t = t / 2) {
            System.out.println(t);
            if ((val & t) != 0) System.out.println(" 1");
            else System.out.println(" 0");
        }
    }
}

In particular, I am not sure why we are using val=123 ?特别是,我不确定为什么我们使用val=123 I understand that this program will print out 123 in binary but why is that the case?我知道这个程序会以二进制形式打印出 123 但为什么会这样呢? How does this work?这是如何运作的? I do understand however, the principles of the & operator and how you can turn on and off bits but I am not sure how it works in this particular example?但是,我确实理解&运算符的原理以及如何打开和关闭位,但我不确定它在此特定示例中的工作原理?

This program will print out the binary digits of the number in val from MSB to LSB by comparing it to each power of 2:该程序将通过与 2 的每个幂进行比较,将val数字的二进制数字从 MSB 打印到 LSB:

123 : 01111011 &
128 : 10000000 = 
      00000000 

      00000000 != 0 => false, print 0

123 : 01111011 &
 64 : 01000000 = 
      01000000 

      01000000 != 0 =>  true, print 1

123 : 01111011 &
 32 : 00100000 = 
      00100000 

      00100000 != 0 =>  true, print 1

// repeat for 2^4-2^1... 

123 : 01111011 &
  1 : 00000001 = 
      00000001 

      00000001 != 0 =>  true, print 1

Very simple:很简单:

It just checks if the value (123 in this case) using the bitwise operator &.它只是使用按位运算符 & 检查值(在本例中为 123)。 The result of that is 1 or 0, this process is repeated for the following value 0.5t etc until t=0, resulting in the binary string for this value 123.其结果为 1 或 0,此过程对下一个值 0.5t 重复,直到 t=0,产生此值 123 的二进制字符串。

暂无
暂无

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

相关问题 有人请向我解释这个 - Someone please explain this to me 有人可以在休眠中解释我@MapsId 吗? - can someone please explain me @MapsId in hibernate? java 中的数据源是什么? 有人可以用简单的语言向我解释吗? - What is a datasource in java? Can someone please explain me in simple language? 有人可以解释一下hashmap get(key)方法的代码吗? - Can someone please explain me the code for the hashmap get(key) method? 有人可以告诉我这里的Java代码在做什么吗? - Can someone please explain to me what the java code here is doing? 我不知道JMSExceptions是什么,以及如何处理它们。 有人可以向我解释一下吗? - I don't know what JMSExceptions are, and how to handle them. Can someone explain this to me please? 有人可以解释一下下面这段Java代码中的Node到底是什么吗? - Can someone please explain me what exactly is Node in this below piece of code in java? 我不明白这段代码背后的逻辑。 有人可以向我解释它的真正作用和方式吗? - i do not get the logic behind this code. Can someone please explain to me what it really does and how? 有人可以向我解释一下此web.xml文件中发生了什么(安全性约束) - Can someone please explain to me what is happening in this web.xml file (security-constraints) 有人可以解释一下此正则表达式吗? ^(?=。* prodCode =)。* $ - Can someone please explain this regex? ^(?=.*prodCode=).*$
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM