(Java) Specify number of bits (length) when converting binary number to string?

后端 未结 8 1194
有刺的猬
有刺的猬 2020-12-30 13:03

I\'m trying to store a number as a binary string in an array but I need to specify how many bits to store it as.

For example, if I need to store 0 with two bits I ne

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 13:41

    import java.util.BitSet;
    
    public class StringifyByte {
    
        public static void main(String[] args) {
            byte myByte = (byte) 0x00;
            int length = 2;
            System.out.println("myByte: 0x" + String.valueOf(myByte));
            System.out.println("bitString: " + stringifyByte(myByte, length));
    
            myByte = (byte) 0x0a;
            length = 6;
            System.out.println("myByte: 0x" + String.valueOf(myByte));
            System.out.println("bitString: " + stringifyByte(myByte, length));
        }
    
        public static String stringifyByte(byte b, int len) {
            StringBuffer bitStr = new StringBuffer(len);
            BitSet bits = new BitSet(len);
            for (int i = 0; i < len; i++)
            {
               bits.set (i, (b & 1) == 1);
               if (bits.get(i)) bitStr.append("1"); else bitStr.append("0");
               b >>= 1;
            }
            return reverseIt(bitStr.toString());
        }
    
        public static String reverseIt(String source) {
            int i, len = source.length();
            StringBuffer dest = new StringBuffer(len);
    
            for (i = (len - 1); i >= 0; i--)
               dest.append(source.charAt(i));
            return dest.toString();
        }
    }
    

    Output:

    myByte: 0x0
    bitString: 00
    myByte: 0x10
    bitString: 001010
    

提交回复
热议问题