将二进制序列存储在字节数组中?

Store binary sequence in byte array?(将二进制序列存储在字节数组中?)
本文介绍了将二进制序列存储在字节数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要将一对长度为 16 位的二进制序列存储到一个字节数组(长度为 2)中.一个或两个二进制数不会改变,因此进行转换的函数可能是矫枉过正的.例如,16 位二进制序列是 1111000011110001.如何将其存储在长度为 2 的字节数组中?

I need to store a couple binary sequences that are 16 bits in length into a byte array (of length 2). The one or two binary numbers don't change, so a function that does conversion might be overkill. Say for example the 16 bit binary sequence is 1111000011110001. How do I store that in a byte array of length two?

推荐答案

    String val = "1111000011110001";
    byte[] bval = new BigInteger(val, 2).toByteArray();

还有其他选择,但我发现最好使用 BigInteger 类,它可以转换为字节数组,来解决这类问题.我更喜欢 if,因为我可以从 String 实例化类,它可以表示各种基数,如 8、16 等,也可以这样输出.

There are other options, but I found it best to use BigInteger class, that has conversion to byte array, for this kind of problems. I prefer if, because I can instantiate class from String, that can represent various bases like 8, 16, etc. and also output it as such.

public static byte[] getRoger(String val) throws NumberFormatException,
        NullPointerException {
    byte[] result = new byte[2];
    byte[] holder = new BigInteger(val, 2).toByteArray();
    
    if (holder.length == 1) result[0] = holder[0];
    else if (holder.length > 1) {
        result[1] = holder[holder.length - 2];
        result[0] = holder[holder.length - 1];
    }
    return result;
}

例子:

int bitarray = 12321;
String val = Integer.toString(bitarray, 2);
System.out.println(new StringBuilder().append(bitarray).append(':').append(val)
  .append(':').append(Arrays.toString(getRoger(val))).append('
'));

这篇关于将二进制序列存储在字节数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Android schema validation(Android 架构验证)
Required Multiple beans of same type in Spring(Spring中需要多个相同类型的bean)
How to deal with JAXB ComplexType with MixedContent data?(如何处理带有 MixedContent 数据的 JAXB ComplexType?)
Validate an XML File Against Multiple Schema Definitions(针对多个模式定义验证 XML 文件)
JAXB - Property quot;Valuequot; is already defined. Use lt;jaxb:propertygt; to resolve this conflict(JAXB - 属性“值;已经定义了.使用 lt;jaxb:propertygt;解决这个冲突)
XML instance generation from XML schema (xsd)(从 XML 模式 (xsd) 生成 XML 实例)