如何在字节数组上添加填充? [英] How to add padding on to a byte array?

查看:109
本文介绍了如何在字节数组上添加填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在大小 8 byteArray中具有此 40位键,我想对其添加0填充,直到其变为 56位.

I have this 40 bit key in a byteArray of size 8, and I want to add 0 padding to it until it becomes 56 bit.

byte[] aKey = new byte [8];  // How I instantiated my byte array

有什么想法吗?

推荐答案

一个8字节的数组为64位.如果将数组初始化为

An 8 byte array is of 64 bits. If you initialize the array as

byte[] aKey = new byte [8]

所有字节均以0初始化.如果您设置前40位(即5字节),那么其他3个字节(即41至64位)仍设置为0.因此,默认情况下,您将第41位至第56位设置为0,而您没有不必重置它们.

all bytes are initialized with 0's. If you set the first 40 bits, that is 5 bytes, then your other 3 bytes, i.e, from 41 to 64 bits are still set to 0. So, you have by default from 41st bit to 56th bit set to 0 and you don't have to reset them.

但是,如果您的数组已经用某些值初始化,并且您希望将位从41清除为56,则有几种方法可以执行此操作.

However, if your array is already initialized with some values and you want to clear the bits from 41 to 56, there are a few ways to do that.

第一: 您只需将aKey[5] = 0aKey[6] = 0设置为0,即可将第41个字节和第7个字节(由第41位到第56位组成)设置为0

First: you can just set aKey[5] = 0 and aKey[6] = 0 This will set the 6th bye and the 7th byte, which make up from 41st to 56th bit, to 0

第二个::如果要处理位,则还可以使用BitSet.但是,就您而言,我认为第一种方法要容易得多,尤其是如果您使用Java 7之前的版本,则以下某些方法不存在,因此必须编写

Second: If you are dealing with bits, you can also use BitSet. However, in your case, I see first approach much easier, especially, if you are pre Java 7, some of the below methods do not exist and you have to write your own methods to convert from byte array to bit set and vice-versa.

byte[] b = new byte[8];
BitSet bitSet = BitSet.valueOf(b);
bitSet.clear(41, 56); //This will clear 41st to 56th Bit
b = bitSet.toByteArray();

注意:BitSet.valueOf(byte[])BitSet.toByteArray()仅在Java 7中存在.

Note: BitSet.valueOf(byte[]) and BitSet.toByteArray() exists only from Java 7.

这篇关于如何在字节数组上添加填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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