Java中的二进制表示 [英] Binary representation in Java

查看:182
本文介绍了Java中的二进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现很难理解并使用java中的二进制表示法:

I am finding it difficult to understand and work with this binary representation in java:

在用户Jon Skeet的帮助下,我明白二进制表示应该是以这种方式构建。

With the help of the user Jon Skeet, I understood that binary representation should be built this way.

这是一个代码示例:

public class chack {

public static void main(String[] args) {
    int num2=2;
    int num3=3;
    int num4=4;
    int num1=1;
    int nirbinary = (num1 << 24) | (num2 << 16) | (num3 << 8) | num4;
    System.out.println(nirbinary);
    String nir=  Integer.toBinaryString(nirbinary);
    System.out.println(nir);
    }
}

几个问题:


  1. 如何从已经在这个二进制文件中的int中获取num1(例如)

  2. 为什么我会得到 16909060 当我打印 nirbinary 时 - 它代表什么?
    如何从已经在这个二进制
    表示中的int获得num1(例如)?

  1. How does one get num1 (for example) back from an int who is already in this binary
  2. why do I get 16909060 when I print nirbinary- what does it stands for? How does one get num1 (for example) back from an int who is already in this binary representation?

谢谢

推荐答案

16909060 代表号码16909060。

16909060 stands for the number 16909060.

(1 * 2 24 )+(2 * 2 16 )+(3 * 2 8 )+ 4

It is (1 * 224) + (2 * 216) + (3 * 28) + 4.

要获得 num1 退出,只需将结果右移即可你左移和掩盖其他字节的数量相同( num1 (*)并非总是必需,但对于其他字节):

To get num1 back out, just right-shift the result the same amount you left-shifted and mask out the other bytes (not always necessary for num1(*), but for the others):

int num1 = nirbinary >> 24 & 0xFF;
int num2 = nirbinary >> 16 & 0xFF;
int num3 = nirbinary >> 8 & 0xFF;
int num4 = nirbinary & 0xFF;

请注意 nirbinary 不是二进制表示。或者更准确地说:它不是或多于或少于二元 num1 num2 num3 num4 :内部所有数字(以及字符和布尔值......)都以二进制形式存储。

Note that nirbinary is not "a binary representation". Or more precisely: it's no more or less binary than num1, num2, num3 and num4: internally all numbers (and characters, and booleans, ...) are stored in binary.

(*)请注意,如果 num1 > 127,那么 需要使用>使用&> 0xFF 以确保恢复正确的值。 >> >>> 之间的差异是新位插入留下价值的一面:使用>> ,它们将取决于最高值位(称为符号扩展名)和> ;>> 它们将始终为0.

(*) note that if num1 is > 127, then you either need to use >>> to do the right-shift or use the & 0xFF in order to ensure that the correct value is restored. The difference between >> and >>> are the "new" bits inserted on the "left" side of the value: With >> they will depend on the highest-value bit (known as sign-extension) and with >>> they will always be 0.

这篇关于Java中的二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆