BitSet 与 Byte Array 类型转化 转发
2012-08-01 11:14
134 查看
Converting Between
a BitSet and a Byte Array
There are no default methods for converting a BitSet to and from a byte array. This example implements two methods to do the conversion. These methodsmake it possible to easily work with both BitSet and BigInteger and take advantage of their capabilities
when needed.
COPY
// Returns a bitset containing the values in bytes. // The byte-ordering of bytes must be big-endian which means the most significant bit is in element 0. public static BitSet fromByteArray(byte[] bytes) { BitSet bits = new BitSet(); for (int i=0; i<bytes.length*8; i++) { if ((bytes[bytes.length-i/8-1]&(1<<(i%8))) > 0) { bits.set(i); } } return bits; } // Returns a byte array of at least length 1. // The most significant bit in the result is guaranteed not to be a 1 // (since BitSet does not support sign extension). // The byte-ordering of the result is big-endian which means the most significant bit is in element 0. // The bit at index 0 of the bit set is assumed to be the least significant bit. public static byte[] toByteArray(BitSet bits) { byte[] bytes = new byte[bits.length()/8+1]; for (int i=0; i<bits.length(); i++) { if (bits.get(i)) { bytes[bytes.length-i/8-1] |= 1<<(i%8); } } return bytes; }
//Comments
10 Dec 2010 - 1:46pm by Anonymous (not verified) |
16 Feb 2011 - 12:08pm by Anonymous (not verified) |
相关文章推荐
- C# Bitmap类型与Byte[]类型相互转化
- Byte类型与各种基础类型之间的相互转化函数总结
- Java之——基本数据类型与byte数组相互转化
- java byte类型转化为int (注意加&0xff)
- delphi中如何将string类型的字符串数据转化成byte[]字节数组类型的数据
- 关于String类型数字转化为byte类型及JS中不包含年月日的时间控件
- Java基础---Java---IO流-----对象的序列化、管道流、RandomAccessFile、数据类型的流对象DataStream、ByteArrayStream
- java基本类型和byte数字的转化
- java把byte类型数组转化成对象的步骤。
- C# string类型和Byte[]相互转化
- Java基础---Java---IO流-----对象的序列化、管道流、RandomAccessFile、数据类型的流对象DataStream、ByteArrayStream
- C# Bitmap类型与Byte[]类型相互转化
- 二进制数据解析 + byteArray类型
- Go语言string与[]byte类型转化避免拷贝
- 简单讨论数据类型(byte)强制转化后的数值变化规律
- qt 中文乱码 处理QByteArray类型里含中文的数据
- java中类型int转化为Byte
- VB中 byte数组和其他数据类型之间的转化
- Java byte数组按位转化为long类型
- String 类型转化为Byte[]的代码