简体   繁体   English

如何在java中的dataOutputstream中写入位

[英]How to write bit in dataOutputstream in java

I want to write 2 bytes of data as a bit.我想将 2 个字节的数据写入一点。 My bit value is 00010000 00000000 these two bytes data I want arrange in bit.我的位值是 00010000 00000000 这两个字节的数据我想按位排列。

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 .您不能将单个位写入DataOutputStream The I/O granularity for all Java classes that inherit from OutputStream and InputStream is an 8 bit byte.OutputStreamInputStream继承的所有 Java 类的 I/O 粒度都是 8 位字节。

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;操作系统级 API(系统调用)不支持这一点; read "man 2 read" and "man 2 write" in the UNIX / Linux manual pages.阅读 UNIX/Linux 手册页中的“man 2 read”和“man 2 write”。

  • 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.您写入的地方(文件、套接字、管道等)都由操作系统建模,以 8 位字节作为数据粒度。 You can't write 1 bit to a file without supplying 7 more.如果不提供 7 位,就不能向文件写入 1 位。

  • 8 x N bit granularity applies down at the hardware level for disk controllers, network interfaces and so on. 8 x N 位粒度向下应用于磁盘控制器、网络接口等的硬件级别。 And in the standards for network communication ... right down to ISO/OSI level 1.在网络通信标准中……一直到 ISO/OSI 级别 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.话虽如此,没有什么能阻止您设计和实现您自己的 Java API,它允许您一次写入(或读取)1 位。 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.问题在于,当您开始与操作系统交互时(通过 Java I/O 类或本机代码),您的 API 实现必须写入(或读取)8 x N 位的包。

Has anyone one done this already?有人已经这样做了吗? Well apparently, the answer is "yes".显然,答案是“是的”。 Google for "java bitstream class" or "java bitstream library".谷歌搜索“java 比特流类”或“java 比特流库”。 (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 ...) (抱歉,但没有链接,因为我认为比特流 API 是一个疯狂的想法,我不想鼓励您浪费时间与它们...)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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