在java中设置字节值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18998349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:13:09  来源:igfitidea点击:

Set the Byte values in java

javabytebytearraybit-manipulationbit

提问by rachana

I want to convert the binary string to byte array in java. I have write the code to set every bit of the byte array from the binary string String A = "1000000111010000"

我想将二进制字符串转换为java. 我已经编写了代码来设置二进制字符串中字节数组的每一位String A = "1000000111010000"

        private byte firstByte;
    private byte secondByte;
        byte xByte = new byte[2];

        for(int i=0 ; i<A.length() ;i++){

            if(i<8){
                System.out.println(" i : "+i+" A.char[i] :"+A.charAt(i));
                firstByte = (byte) (firstByte | (A.charAt(i) << i));
            }else{
                System.out.println(" i : "+i+" A.char[i] :"+A.charAt(i));
                secondByte = (byte) (secondByte | (A.charAt(i) << i));
            }
        }
        xByte[0] = firstByte;
        xByte[1] = secondByte;

To write the above code i have taken the help from thislink . But the value get stored int the xByte[0]and xByte[1]is not correct. It gives values like

为了编写上面的代码,我从这个链接中得到了帮助。但是该值被存储在xByte[0]并且xByte[1]是不正确的。它给出了像

                   xByte[0] :-15
                   xByte[1] :0

Is this is the write way?Please suggest me the correction to get the right byte values.

这是写入方式吗?请建议我进行更正以获得正确的字节值。

回答by code_fish

A.charAt[i] will return a char, not a number and you are setting bit to a char value.

A.charAt[i] 将返回一个字符,而不是一个数字,并且您将 bit 设置为一个字符值。

Instead use

而是使用

if(A.charAt[i] == '0')
  firstByte = (byte) (firstByte | (0 << i));
else
   firstByte = (byte) (firstByte | (1 << i));

回答by SudoRahul

You can't simply cast the A.charAt(i)to an int. It'll return the ASCII codeof the 1and 0.

您不能简单地将A.charAt(i)转换为int。它会返回ASCII码的的10

Therefore, you need to do something like this to get their numeric value:-

因此,你需要做这样的事情来获得它们的数值:-

int bit = Character.getNumericValue(A.charAt(i)); // This will give the actual value
...
firstByte = (byte) (firstByte | (bit << i));

回答by Sergej Panic

Just use BinaryCodecfrom Apache Commons:

只需使用Apache Commons 中的BinaryCodec

 byte[] bytes = new BinaryCodec().toByteArray("1000000111010000");

   

   

If you want to do such conversion on your own, your code needs some corrections.
You are expecting that A.charAt(i)will return numeric 0 or 1, but will actually return char'0' or '1'. The char data type is a single 16-bit Unicode character with a numeric range from 0 to 2^16, it's values are formally called code points.
To print the code point value you need to cast char to int:

如果你想自己做这样的转换,你的代码需要一些更正。
您期望它A.charAt(i)会返回数字 0 或 1,但实际上会返回char“0”或“1”。char 数据类型是单个 16 位 Unicode 字符,数字范围从 0 到 2^16,它的值正式称为 code points
要打印代码点值,您需要将 char 转换为 int:

System.out.println("Character " + A.charAt(i) + " has a code point numeric value of " + (int)A.charAt(i));

Output for '0' and '1':

'0' 和 '1' 的输出:

Character 0 has a code point numeric value of 48
Character 1 has a code point numeric value of 49

 

 

Operator '<<' convertschar operands to int, therefore this shifting is producing wrong results because:

运算符 '<<'char 操作数转换为 int,因此这种移位会产生错误的结果,因为:

firstByte = (byte) (firstByte | (A.charAt(i) << i));

is the same as

是相同的

firstByte = (byte) (firstByte | ( (int)A.charAt(i) << i));

which for char '0' is the same as shifting value 48 to the left:

对于 char '0' 与将值 48 向左移动相同:

firstByte = (byte) (firstByte | ( 48 << i));

 

 

To convert char '0' or '1' to 0 or 1 numeric value use Character.getNumericValue(A.charAt(i)):

要将字符 '0' 或 '1' 转换为 0 或 1 数值,请使用 Character.getNumericValue(A.charAt(i)):

firstByte = (byte) (firstByte | ( Character.getNumericValue(A.charAt(i)) << i));

   

   

Also shifting by value iis incorrect. You need to shift by (7-i)for the first byte or (7-i%8)for the second byte. When index ireaches 8 it needs to start counting from 0, therefore i%8

按值移动i也是不正确的。您需要(7-i)为第一个字节或(7-i%8)第二个字节移动。当索引i达到 8 时需要从 0 开始计数,因此i%8

   

   

When printing a values for a byte type you have two options: byte numeric value or binary string representation:

打印字节类型的值时,您有两个选择:字节数值或二进制字符串表示:

System.out.println("FIRST  byte numeric value = " + xByte[0] + ", binary string representation = " + Integer.toBinaryString((xByte[0]+256)%256));
System.out.println("SECOND byte numeric  value = " + xByte[1] + ", binary string representation = " + Integer.toBinaryString((xByte[1]+256)%256));

output:

输出:

FIRST  byte value = -127, binary representation = 10000001
SECOND byte value = -48, binary representation = 11010000

Whole corrected example:

整个更正示例:

public class ByteTest
{

  public static void main(String[] args)
  {

    byte firstByte=0;
    byte secondByte=0;

    String A = "1000000111010000";
    byte[] xByte = new byte[2];





    for(int i=0 ; i<A.length() ;i++){

      System.out.println("Character " + A.charAt(i) + " has a code point numeric value of " + (int)A.charAt(i));

      if(i<8){
        System.out.println(" i : "+i+" A.char[i] :"+A.charAt(i));
        firstByte = (byte) (firstByte | (Character.getNumericValue(A.charAt(i)) << (7-i)));
      }else{
        System.out.println(" i : "+i+" A.char[i] :"+A.charAt(i));
        secondByte = (byte) (secondByte | (Character.getNumericValue(A.charAt(i)) << (7-i%8)));
      }
    }
    xByte[0] = firstByte;
    xByte[1] = secondByte;


    System.out.println("FIRST  byte numeric value = " + xByte[0] + ", binary string representation = " + Integer.toBinaryString((xByte[0]+256)%256));
    System.out.println("SECOND byte numeric  value = " + xByte[1] + ", binary string representation = " + Integer.toBinaryString((xByte[1]+256)%256));




  }

}