简体   繁体   中英

How to write bit in dataOutputstream in java

I want to write 2 bytes of data as a bit. My bit value is 00010000 00000000 these two bytes data I want arrange in bit.

Requirement:

1 bit - 0
1 bit - 0 
1 bit - 0 
1 bit - 1
1 bit - 0 
1 bit - 0 
1 bit - 0 
1 bit - 0 


4 bit - 0
1 bit - 0 
1 bit - 0 
2 bit - 0

You cannot write a single bit to a DataOutputStream . The I/O granularity for all Java classes that inherit from OutputStream and InputStream is an 8 bit byte.

There are a few reasons for this:

  • Efficiency - the cost of writing data one bit at a time is prohibitive.

  • The OS-level API's (syscalls) do not support this; read "man 2 read" and "man 2 write" in the UNIX / Linux manual pages.

  • The places you are writing to (files, sockets, pipes and so on) are all modelled by the operating system with 8 bit bytes as the data granularity. You can't write 1 bit to a file without supplying 7 more.

  • 8 x N bit granularity applies down at the hardware level for disk controllers, network interfaces and so on. And in the standards for network communication ... right down to ISO/OSI level 1.


Having said that, there is nothing stopping you from designing and implementing your own Java API that allows you to write (or read) 1 bit at a time. The problem is that at the point you come to interact with the operating system (either via Java I/O classes, or in native code), your API's implementation has to be writing (or reading) bundles of 8 x N bits.

Has anyone one done this already? Well apparently, the answer is "yes". Google for "java bitstream class" or "java bitstream library". (Sorry, but no links because I think bitstream APIs are a nutty idea, and I don't want to encourage you to waste your time with them ...)

可以通过 JBBPBitOutputStream 或 JBBPOut 使用JBBP 框架将位写入 OutputStream

JBBPOut.BeginBin().Bit(false,false,false,true,true,true).End().toByteArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM