如何二进制字符串转换成的在Java 2个字节的字节数组 [英] How to convert binary string to the byte array of 2 bytes in java

查看:439
本文介绍了如何二进制字符串转换成的在Java 2个字节的字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有二进制串字符串A =1000000110101110。我想这个字符串转换为长度为2的字节数组转换在的Java

I have binary string String A = "1000000110101110". I want to convert this string into byte array of length 2 in java

我已此链接

我曾尝试将其转换成通过各种途径字节

I have tried to convert it into byte by various ways


  1. 我已经转换该字符串成十进制,然后再应用code储存入字节数组

  1. I have converted that string into decimal first and then apply the code to store into the byte array

int aInt = Integer.parseInt(A, 2);
        byte[] xByte = new byte[2];
    xByte[0] = (byte) ((aInt >> 8) & 0XFF);
    xByte[1] = (byte) (aInt & 0XFF);
    System.arraycopy(xByte, 0, record, 0,
            xByte.length);


但得到的值存储入字节数组是否定的。

But the values get store into the byte array are negative

xByte[0] :-127
xByte[1] :-82

这是错误的值。

2.我已经使用也尝试

2.I have also tried using

byte[] xByte = ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(aInt).array();

但在像上面的行抛出异常

But it throws the exception at the above line like

  java.nio.Buffer.nextPutIndex(Buffer.java:519)     at
  java.nio.HeapByteBuffer.putInt(HeapByteBuffer.java:366)   at
  org.com.app.convert.generateTemplate(convert.java:266)

我应该怎么做,现在在二进制串到字节的2个字节数组转换?是否有 Java的任何内置的功能来得到字节数组

推荐答案

你所得到的答案

 xByte[0] :-127
 xByte[1] :-82

是正确的。

这就是所谓2的恭维重新presantation。
第1位被用作符号位。

This is called 2's compliment Represantation. 1st bit is used as signed bit.

0 for +ve
1 for -ve

如果第1位是0比计算作为常规。
但是,如果第1位是1比128扣除7位的值,什么都回答是-ve形式psented $ P $。

if 1st bit is 0 than it calculates as regular. but if 1st bit is 1 than it deduct the values of 7 bit from 128 and what ever the answer is presented in -ve form.

在你的情况
第一个值是 10000001
所以1(第1位)为-ve和128 - 1(最后七个位)= 127
所以值为-127

In your case 1st value is10000001 so 1(1st bit) for -ve and 128 - 1(last seven bits) = 127 so value is -127

有关详细阅读2的补再presentation。

For more detail read 2's complement representation.

这篇关于如何二进制字符串转换成的在Java 2个字节的字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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