代码之家  ›  专栏  ›  技术社区  ›  echoblaze

爪哇中的位操作与输出

  •  5
  • echoblaze  · 技术社区  · 17 年前

    如果您有二进制字符串(字面上是只包含1和0的字符串对象),如何将它们作为位输出到文件中?

    这是我正在研究的一个文本压缩程序;它仍然困扰着我,最后让它工作会很好。谢谢!

    4 回复  |  直到 17 年前
        1
  •  6
  •   Tomer Gabel    17 年前

    
    byte[] buffer = new byte[ ( string.length + 7 ) / 8 ];
    for ( int i = 0; i < buffer.length; ++i ) {
       byte current = 0;
       for ( int j = 7; j >= 0; --j )
           if ( string[ i * 8 + j ] == '1' )
               current |= 1 << j;
       output( current );
    }
    

        2
  •  6
  •   finnw    17 年前

    String s = "11001010001010101110101001001110";
    byte[] bytes = (new java.math.BigInteger(s, 2)).toByteArray();
    

        3
  •  2
  •   izb    17 年前
    public class BitOutputStream extends FilterOutputStream
    {
        private int buffer   = 0;
        private int bitCount = 0;
    
        public BitOutputStream(OutputStream out)
        {
            super(out);
        }
    
        public void writeBits(int value, int numBits) throws IOException
        {
            while(numBits>0)
            {
                numBits--;
                int mix = ((value&1)<<bitCount++);
                buffer|=mix;
                value>>=1;
                if(bitCount==8)
                    align8();
            }
        }
    
        @Override
        public void close() throws IOException
        {
            align8(); /* Flush any remaining partial bytes */
            super.close();
        }
    
        public void align8() throws IOException
        {
            if(bitCount > 0)
            {
                bitCount=0;
                write(buffer);
                buffer=0;
            }
        }
    }
    

    if (nextChar == '0')
    {
        bos.writeBits(0, 1);
    }
    else
    {
        bos.writeBits(1, 1);
    }
    
        4
  •  1
  •   David L    17 年前

    String s = "11001010001010101110101001001110";
    byte[] data = new byte[s.length() / 8];
    for (int i = 0; i < data.length; i++) {
        data[i] = (byte) Integer.parseInt(s.substring(i * 8, (i + 1) * 8), 2);
    }
    

    FileOutputStream