编码数字的字节数

时间:2011-04-29 11:47:25

标签: java byte bytearray

这可能是一个初学Java问题,但我希望能够计算存储整数所需的字节数。并将该数字转换为字节数组。它与我正在执行的一些TLV编码有关。我意识到Java存储了两个完整的东西,但我忽略了这一点,我只是想保留二进制表示。

例如,如果您的数字为256,则需要2个字节(因为1个字节可以存储2 ^ 8-1,我认为)然后我想将该数字转换为字节数组。

其中:

byte [0] = 1111 1111

byte [1] = 0000 0001

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

您可以使用Math.ceil(Math.log(number) / Math.log(2))获取bits的数量,以二进制格式存储您的号码。如果偏差为8,您将获得bytes来存储您的电话号码。

答案 1 :(得分:3)

数字的二进制对数(log2)为您提供显示数字所需的位数。从那里应该很容易得到字节。

答案 2 :(得分:2)

由于Java只包含log10,因此必须先将其转换为log2。考虑基数变化的定义 enter image description here

然后我们可以为建议的答案编写 Math.ceil(Math.log(256)/ Math.log(2)) ...例如,你需要9位才能保存256或2个字节:

    System.out.println(Integer.toBinaryString(256));
    int numberBits = (int) Math.ceil(Math.log(256) / Math.log(2)) + 1;
    int numberBytes = (int) (Math.ceil(Math.log(256) / Math.log(2)) / 8) + 1;
    System.out.println(numberBits);
    System.out.println(numberBytes);

100000000
9
2

我对如何获取你的需求的byte []感兴趣(让它们按照恢复顺序)......我开始使用char []实现以下测试类。然后,我想到如果你需要对位集进行操作,你也可以使用BitSet。

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;

public class TestRevertBitSet {

    public static class RevertableBitSet {

        private BitSet bitSet;
        private boolean flipped;

        private RevertableBitSet(BitSet bitSet) {
            this.bitSet = bitSet;
        }

        public static RevertableBitSet makeNew(char[] bitArray) {
            BitSet byteValue = new BitSet(bitArray.length);
            for (int i = 0; i < bitArray.length; i++) {
                if (bitArray[i] == '1') {
                    byteValue.flip(i);
                }
            }
            RevertableBitSet r = new RevertableBitSet(byteValue);
            if (r.hasZeroCardinality()) {
                r.flipAllBitsTrue();

            } else {
                r.revertBitsOrder();
            }
            return r;
        }

        public boolean hasAllBitsFlip() {
            return this.flipped;
        }

        /**
         * @return if all the bits are set.
         */
        public boolean hasZeroCardinality() {
            return this.bitSet.cardinality() == 0;
        }

        /**
         * Flips all bits from the given bitSet to true.
         */
        public void flipAllBitsTrue() {
            this.bitSet.set(0, this.bitSet.size());
            this.flipped = true;
        }

        /**
         * Reverts the bits sequence. For instance, from 01100 to 00110.
         */
        public void revertBitsOrder() {
            for (int i = 0; i < 4; i++) {
                boolean nthBit = this.bitSet.get(i);
                this.bitSet.set(i, this.bitSet.get(7 - i));
                this.bitSet.set(7 - i, nthBit);
            }
        }

        /**
         * @return a char array with values based on the bit indexes of the
         *         given bit set.
         */
        public char[] toCharArray() {
            char[] bitChars = new char[8];
            for (int i = 0; i < bitChars.length; i++) {
                bitChars[i] = bitSet.get(i) ? '1' : '0';
            }
            return bitChars;
        }

        /**
         * @param bitIndex
         * @return the boolean value of the given bit index.
         */
        public boolean getBitBooleanAtIndex(int bitIndex) {
            if (bitIndex > 7) {
                return false;
            }
            return this.bitSet.get(bitIndex);
        }

        /**
         * @param byteSetsList
         *            is the list of BitSet.
         * @return the integer representation of the entire bit set.
         */
        public static int convertSetToInteger(
                List<RevertableBitSet> byteSetsList) {
            int sum = 0;
            int index = 0;
            for (RevertableBitSet bitSet : byteSetsList) {
                if (bitSet.hasAllBitsFlip()) {
                    for (int i = 0; i < 8; i++) {
                        index++;
                    }
                    continue;
                }
                for (int i = 7; i >= 0; i--) {
                    int bit = bitSet.getBitBooleanAtIndex(i) ? 1 : 0;
                    int intValue = (int) Math.pow((double) 2, (double) index++)
                            * bit;
                    sum = sum + intValue;
                }
            }
            return sum;
        }

        @Override
        public String toString() {
            StringBuilder b = new StringBuilder();
            b.append("[ ");
            for (int i = 0; i < 7; i++) {
                b.append(i);
                b.append(" , ");
            }
            b.delete(0, b.length() - 2);
            b.append(" ]");
            return b.toString();
        }
    }

    public static void main(String[] args) throws IOException {

        int decimalNumber = 256;
        System.out.println("Decimal Number: " + decimalNumber);
        System.out.println(Integer.toBinaryString(decimalNumber));
        int numberBits = (int) Math.ceil(Math.log(decimalNumber) / Math.log(2)) + 1;
        int numberBytes = (int) (Math.ceil(Math.log(decimalNumber)
                / Math.log(2)) / 8) + 1;
        System.out.println("Number of bits: " + numberBits);
        System.out.println("Number of bytes: " + numberBytes);

        List<RevertableBitSet> bytesSet = new ArrayList<RevertableBitSet>();

        int bitsCounter = -1;
        char[] binaryChars = Integer.toBinaryString(decimalNumber)
                .toCharArray();
        char[] currentChars = new char[8];
        Arrays.fill(currentChars, '0');
        for (int i = binaryChars.length - 1; i >= 0; i--) {
            if (bitsCounter + 1 <= 7) {
                currentChars[++bitsCounter] = binaryChars[i];

            } else {
                RevertableBitSet bitSet = RevertableBitSet
                        .makeNew(currentChars);
                bytesSet.add(bitSet);

                bitsCounter = -1;
                Arrays.fill(currentChars, '0');
                currentChars[++bitsCounter] = binaryChars[i];
            }
        }

        bytesSet.add(RevertableBitSet.makeNew(currentChars));

        System.out.println("------------");

        for (RevertableBitSet bitSet : bytesSet) {
            System.out.println(Arrays.toString(bitSet.toCharArray()));
        }

        System.out.println("------------");
        System.out.println("Number: "
                + RevertableBitSet.convertSetToInteger(bytesSet));
    }
}

执行main方法的输出是:

Decimal Number: 256
100000000
Number of bits: 9
Number of bytes: 2
------------
[1, 1, 1, 1, 1, 1, 1, 1]
[0, 0, 0, 0, 0, 0, 0, 1]
------------
Number: 256

更大的数字以及工作......

Decimal Number: 33456176
1111111101000000000110000
Number of bits: 26
Number of bytes: 4
------------
[0, 0, 1, 1, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
------------
Number: 33456176