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('
'));
这篇关于将二进制序列存储在字节数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将二进制序列存储在字节数组中?
基础教程推荐
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- JPA惰性列表上的流 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
