Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将int转换为byte[]并从byte[]重新转换值_Java - Fatal编程技术网

Java 如何将int转换为byte[]并从byte[]重新转换值

Java 如何将int转换为byte[]并从byte[]重新转换值,java,Java,我认为int和byte[]之间的转换非常简单,我尝试将一个值转换为byte[],然后在其他函数中重新转换该值以获得int;和字节[]y;,铸造y=(字节[])x,未工作。 我该怎么做?我想要的,例如: in func1 in func2 int x ; x value is casted in the y y is taken and x value is byte[]

我认为int和byte[]之间的转换非常简单,我尝试将一个值转换为byte[],然后在其他函数中重新转换该值以获得int;和字节[]y;,铸造y=(字节[])x,未工作。 我该怎么做?我想要的,例如:

                       in func1                          in func2
int x ;         x value is casted in the y        y is taken and x value is 
byte[] y;                                             extracted

       ------func1-----------  --------func2---------
       ^                    ^ ^                     ^
x = 33 ==feed into==> byte [] ===> extraction ===> 33 
使用类

班级


在Java中,您不能使用类型转换来完成这种事情。这些都是转换,必须通过编程来完成

例如:

    int input = ...
    byte[] output = new byte[4];
    output[0] = (byte) ((input >> 24) & 0xff);
    output[1] = (byte) ((input >> 16) & 0xff);
    output[2] = (byte) ((input >> 8) & 0xff);
    output[3] = (byte) (input & 0xff);
(有更优雅的方式来进行这种特殊的转换。)

字节[]
到“其他东西”类似地是一种转换。。。这可能是也可能不是,取决于“其他东西”是什么

要转换回整数,请执行以下操作:

    byte[] input = ... 
    int output = (input[0] << 24) | (input[1] << 16) | (input[2] << 8) | input[3]
byte[]输入=。。。

int output=(输入[0],但我的数字不是0xABABABAB的形式。对于我的情况,还有一些是int。可能吗
    int input = ...
    byte[] output = new byte[4];
    output[0] = (byte) ((input >> 24) & 0xff);
    output[1] = (byte) ((input >> 16) & 0xff);
    output[2] = (byte) ((input >> 8) & 0xff);
    output[3] = (byte) (input & 0xff);
    byte[] input = ... 
    int output = (input[0] << 24) | (input[1] << 16) | (input[2] << 8) | input[3]