Bitwise IO: Difference between revisions

41,035 bytes added ,  1 month ago
Replace deprecated functions
No edit summary
(Replace deprecated functions)
 
(24 intermediate revisions by 10 users not shown)
Line 1:
{{task}}[[Category:Bitwise operations]]
{{task}}The aim of this task is to write functions (or create a class if your
language is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a <tt>asciiprint "STRING"</tt> is the ASCII byte sequence
Line 22:
* Errors handling is not mandatory
<br><br>
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">T BitWriter
FileWr out
accumulator = 0
bcount = 0
 
F (fname)
.out = File(fname, WRITE)
 
F _writebit(bit)
I .bcount == 8
.flush()
I bit > 0
.accumulator [|]= 1 << (7 - .bcount)
.bcount++
 
F writebits(bits, =n)
L n > 0
._writebit(bits [&] 1 << (n - 1))
n--
 
F flush()
.out.write_bytes([Byte(.accumulator)])
.accumulator = 0
.bcount = 0
 
F close()
.flush()
.out.close()
 
T BitReader
File input
accumulator = 0
bcount = 0
read = 0
 
F (fname)
.input = File(fname)
 
F _readbit()
I .bcount == 0
V a = .input.read_bytes(at_most' 1)
I !a.empty
.accumulator = a[0]
.bcount = 8
.read = a.len
V rv = (.accumulator [&] (1 << (.bcount - 1))) >> (.bcount - 1)
.bcount--
R rv
 
F readbits(=n)
V v = 0
L n > 0
v = (v << 1) [|] ._readbit()
n--
R v
 
V writer = BitWriter(‘bitio_test.dat’)
V chars = ‘12345abcde’
L(ch) chars
writer.writebits(ch.code, 7)
writer.close()
 
V reader = BitReader(‘bitio_test.dat’)
[Char] charsa
L
V x = reader.readbits(7)
I reader.read == 0
L.break
charsa.append(Char(code' x))
print(charsa.join(‘’))</syntaxhighlight>
 
{{out}}
<pre>
12345abcde
</pre>
 
=={{header|6502 Assembly}}==
===Storing Bytes As ASCII Strings===
This routine converts a byte to a sequence of ASCII zeroes and ones, and stores them in a null-terminated string. Works in Easy6502.
Multiple bytes can be stored this way simply by loading a new value in the accumulator and calling the subroutine again. Since Y is still pointed at the null terminator, no re-adjustment of <code>z_BC</code> or Y is necessary.
<lang 6502asm>define StringRam $1200 ;not actually used in the code, but it's here for clarity.
<syntaxhighlight lang="6502asm">
define StringRam $1200 ;not actually used in the code, but it's here for clarity.
define z_BC $00 ;fake Z80-style register for pseudo-16-bit operations.
define z_C $00 ;6502 uses the low byte as the reference point for indirect lookups.
Line 63 ⟶ 145:
lda #$00 ;load the null terminator
sta (z_BC),y ;store the null terminator after the string
rts</langsyntaxhighlight>
 
{{out}}
Line 70 ⟶ 152:
</pre>
 
===Compressing a String of ASCII Zeroes and Ones===
Building on the above, the process can be reversed. The output of the first function becomes the input of the second. Some of the above is repeated, this is to show the two working in sequence.
<syntaxhighlight lang="6502asm">define StringRam $1200
define BitRam $1400
define z_BC $00
define z_C $00
define z_B $01
define z_DE $02
define z_E $02
define z_D $03
define tempMath $04
define tempBitMask $05
define tempY $06
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LDA #0
TAX
TAY ;clear data regs (not needed on Easy6502 but it's a good practice at the start of a program on real hardware)
 
loop_clearRam:
STA $1200,x
STA $1400,x
inx
bne loop_clearRam
 
lda #$12
sta z_B
lda #$00
sta z_C
 
lda #$57
jsr Hex2BinAscii ;store first string
 
lda #$50
jsr Hex2BinAscii ; store second string
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LDA #$12
STA z_B
LDA #$00
STA z_C ; get address of string Ram (this step isn't necessary as they're already loaded but it's here for clarity)
 
LDA #$14
STA z_D
LDA #$00
STA z_E ; get address of destination
 
LDY #$00
STY tempY ; the indices into StringRam and BitRam are different.
 
jsr CompressBits
brk
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Hex2BinAscii:
; this procedure is the same as the above example.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CompressBits:
; takes a stream of ascii zeroes and ones,
; and packs them into a series of bytes.
 
LDX #8 ; repeat 8 times.
LDA #0
STA tempMath ;zero out tempMath
;;;;;;;;;;;;;;;;;;;;;;;;;
loop_CompressBits:
LDA (z_BC),y
beq Terminated ; if the value read is equal to the null terminator, we are done.
; value is assumed to equal #$30 for 0 or #$31 for 1.
ror ; bottom bit of accumulator is rotated into the carry flag.
rol tempMath ; the carry is shifted into the bottom of tempMath.
; repeating this with each successive ascii bit representation
; will preserve the order of the bits. It's hard to explain without drawing a picture
; but trust me it just works.
iny ; next Y
dex
bne loop_CompressBits
;;;;;;;;;;;;;;;;;;;;;;;;;
; loop overhead
tya
pha ; backup source index.
ldy tempY
lda tempMath
sta (z_DE),y
inc tempY ; increment destination index
pla
tay ; restore source index
jmp CompressBits ; back to top
;;;;;;;;;;;;;;;;;;;;;;;;;
Terminated:
rts</syntaxhighlight>
{{out}}
<pre>
1200: 30 31 30 31 30 31 31 31 30 31 30 31 30 30 30 30
1210: 00 (this is the null terminator)
1400: 57 50
</pre>
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Streams; use Ada.Streams;
with Ada.Finalization;
 
Line 91 ⟶ 269:
end record;
overriding procedure Finalize (Stream : in out Bit_Stream);
end Bit_Streams;</langsyntaxhighlight>
The package provides a bit stream interface to a conventional stream. The object of Bit_Stream has a discriminant of any stream type. This stream will be used for physical I/O. Bit_Stream reads and writes arrays of bits. There is no need to have flush procedure, because this is done upon object destruction. The implementation is straightforward, big endian encoding of bits into Stream_Element units is used as required by the task:
<langsyntaxhighlight lang="ada">package body Bit_Streams is
procedure Finalize (Stream : in out Bit_Stream) is
begin
Line 125 ⟶ 303:
end loop;
end Write;
end Bit_Streams;</langsyntaxhighlight>
Example of use:
<langsyntaxhighlight lang="ada">with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with Bit_Streams; use Bit_Streams;
 
Line 159 ⟶ 337:
raise Data_Error;
end if;
end Test_Bit_Streams;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1 - no extensions to language used}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<langsyntaxhighlight lang="algol68"># NIBBLEs are of any width, eg 1-bit OR 4-bits etc. #
MODE NIBBLE = STRUCT(INT width, BITS bits);
 
Line 295 ⟶ 472:
example uudecode nibble stream;
example uuencode nibble stream;
example compress 7bit chars</langsyntaxhighlight>
{{out}}
<pre>
Line 313 ⟶ 490:
STRING & ABACUS => 101001110101001010010100100110011101000111010000001001100100000100000110000101000001100001110101011010011
</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">file = %A_WorkingDir%\z.dat
IfExist, %A_WorkingDir%\z.dat
FileDelete %file%
Line 440 ⟶ 616:
Totalread += 0 ; convert to original format
Return TotalRead
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> file$ = @tmp$ + "bitwise.tmp"
test$ = "Hello, world!"
Line 486 ⟶ 661:
v% = v% << 1 OR (a% >> c%) AND 1
ENDWHILE
= v%</langsyntaxhighlight>
{{out}}
<pre>
Hello, world!
</pre>
=={{header|Binary Lambda Calculus}}==
As explained on https://www.ioccc.org/2012/tromp/hint.html, BLC program
<pre>44 68 16 05 7e 01 17 00 be 55 ff f0 0d c1 8b b2 c1
b0 f8 7c 2d d8 05 9e 09 7f bf b1 48 39 ce 81 ce 80</pre>
compresses a string of ASCII "0"/"1" bytes into an 8x smaller stream of bytes, padding the final byte with 0 bits.
 
=={{header|C}}==
MSB in a byte is considered the "first" bit. Read and write methods somewhat mimic fread and fwrite, though there's no fflush-like function because flushing bits into a file is ill-defined (this whole task is pretty ill-defined). Only way to make sure all bits are written to the file is by detaching the bit filter, just like how closing a file flushes out buffer. There's no limit on read/write size, but caller should ensure the buffer is large enough.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 607 ⟶ 787:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
 
Line 754 ⟶ 934:
reader.Align();
}
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
Common Lisp already has tonnes of bitwise-I/O functionality (remember, folks have written operating systems in Lisp …); in particular, READ-SEQUENCE and WRITE-SEQUENCE neatly handle dumping (VECTOR (UNSIGNED-BYTE 8)) objects directly to/from I/O streams with :ELEMENT-TYPE (UNSIGNED-BYTE 8). This is a fairly robust but not very optimized toolkit that shows off changing between vectors of bytes, vectors of characters, and bit-vectors in a few ways.
 
<langsyntaxhighlight lang="lisp">
(defpackage :rosetta.bitwise-i/o
(:use :common-lisp)
Line 902 ⟶ 1,081:
(finish-output *trace-output*))
 
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="lisp">
BITWISE-I/O> (bitwise-i/o-demo)
 
Line 931 ⟶ 1,110:
 
⇒ ABORT
</syntaxhighlight>
</lang>
 
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight lang="d">import std.stdio: File;
import core.stdc.stdio: FILE, fputc, fgetc;
import std.string: representation;
Line 1,067 ⟶ 1,245:
// Should be the same chars as 'data'.
result.assumeUTF.writeln;
}</langsyntaxhighlight>
{{out}}
abcdefghijk
Line 1,074 ⟶ 1,252:
{{libheader| System.Classes}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Bitwise_IO;
 
Line 1,243 ⟶ 1,421:
reader.Free;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,250 ⟶ 1,428:
0x0155
</pre>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module BitwiseIO {
class BitReader {
construct(Byte[] bytes) {
this.bits = bytes.toBitArray();
}
 
private Bit[] bits;
private Int index;
 
Int offset { // readable & writable property "offset"
@Override
Int get() {
return index;
}
 
@Override
void set(Int offset) {
assert 0 <= offset < size;
index = offset;
}
}
 
Int size.get() { // read-only property "size"
return bits.size;
}
 
Boolean eof.get() { // read-only property "eof"
return index >= size;
}
 
Bit readBit() {
return eof ? assert:bounds : bits[index++];
}
 
Byte readByte() {
assert:bounds index + 8 <= size as $"eof (offset={index}, size={size}";
Int start = index;
index += 8;
return bits[start ..< index].toByte();
}
}
 
class BitWriter {
private Bit[] bits = new Bit[];
 
BitWriter writeBit(Bit bit) {
bits.add(bit);
return this;
}
 
BitWriter writeByte(Byte byte) {
bits.addAll(byte.toBitArray());
return this;
}
 
Byte[] bytes.get() {
// "zero fill" the bits to the next byte boundary: if the bits don't currently stop at
// a byte boundary, then calc the number of "extra" bits (bits.size & 0x7) and append
// "fill bits" from the end slice of the array of bits in the byte=0
bits += bits.size & 0x7 == 0 ? [] : Byte:0.toBitArray() [bits.size & 0x7 ..< 8];
return bits.toByteArray();
}
}
 
@Inject Console console;
void run() {
Bit[] orig = [0,1,0,1,0,1,1,1,0,1,0,1,0]; // hexadecimal 57 50 (with LSB padding)
 
val out = new BitWriter();
orig.forEach(bit -> out.writeBit(bit));
 
val bytes = out.bytes;
console.print($"bytes written={bytes}"); // 0x5750
 
val in = new BitReader(bytes);
val test = new Bit[orig.size]((Int i) -> in.readBit());
assert test == orig;
}
}
</syntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(bitwise_io).
-compile([export_all]).
 
Line 1,304 ⟶ 1,565:
end,
Decompressed = decompress(Unpadded),
io:format("~p~n",[Decompressed]).</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="erlang">184> bitwise_io:test_bitstring_conversion().
<<"Hello, Rosetta Code!">>: 160
<<145,151,102,205,235,16,82,223,207,47,78,152,80,67,223,147,42,1:4>>: 140
Line 1,313 ⟶ 1,574:
ok
185> bitwise_io:test_file_io().
<<"Hello, Rosetta Code!">></langsyntaxhighlight>
 
=={{header|Forth}}==
The stream status is kept on the stack ( b m ), where b is the character accumulator
Line 1,320 ⟶ 1,580:
with the MSB. (The writing code was originally used for Mandelbrot generation.)
 
<langsyntaxhighlight lang="forth">\ writing
 
: init-write ( -- b m ) 0 128 ;
Line 1,340 ⟶ 1,600:
: read-bit ( b m -- b' m' f )
dup 0= if 2drop init-read then
2dup and swap 2/ swap ;</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{trans|Wren}}
<syntaxhighlight lang="vbnet">Type BitFilter
nombre As String
accu As Integer
bits As Integer
bw As Integer
br As Integer
offset As Integer
End Type
 
Sub openWriter(bf As BitFilter)
bf.bw = Freefile
Open bf.nombre For Binary Access Write As #bf.bw
End Sub
 
Sub openReader(bf As BitFilter)
bf.br = Freefile
Open bf.nombre For Binary Access Read As #bf.br
bf.offset = 0
End Sub
 
Sub escribe(bf As BitFilter, buf() As Byte, start As Integer, nBits As Integer, shift As Integer)
Dim As Integer index = start + (shift \ 8)
shift Mod= 8
While nBits <> 0 Or bf.bits >= 8
While bf.bits >= 8
bf.bits -= 8
Dim As Byte outByte = ((bf.accu Shr bf.bits) And &hFF)
Put #bf.bw, , outByte
Wend
While bf.bits < 8 And nBits <> 0
Dim As Byte b = buf(index)
bf.accu = (bf.accu Shl 1) Or (((128 Shr shift) And b) Shr (7 - shift))
nBits -= 1
bf.bits += 1
shift += 1
If shift = 8 Then
shift = 0
index += 1
End If
Wend
Wend
End Sub
 
Sub lee(bf As BitFilter, buf() As Byte, start As Integer, nBits As Integer, shift As Integer)
Dim As Integer index = start + (shift \ 8)
shift Mod= 8
While nBits <> 0
While bf.bits <> 0 And nBits <> 0
Dim As Byte mask = 128 Shr shift
buf(index) = Iif((bf.accu And (1 Shl (bf.bits - 1))) <> 0, (buf(index) Or mask) And &hFF, (buf(index) And Not mask) And &hFF)
nBits -= 1
bf.bits -= 1
shift += 1
If shift >= 8 Then
shift = 0
index += 1
End If
Wend
If nBits = 0 Then Exit Sub
Dim As Byte inByte
Get #bf.br, bf.offset + 1, inByte
bf.accu = (bf.accu Shl 8) Or inByte
bf.bits += 8
bf.offset += 1
Wend
End Sub
 
Sub closeWriter(bf As BitFilter)
If bf.bits <> 0 Then
bf.accu Shl= (8 - bf.bits)
Dim As Byte outByte = (bf.accu And &hFF)
Put #bf.bw, , outByte
End If
Close #bf.bw
bf.accu = 0
bf.bits = 0
End Sub
 
Sub closeReader(bf As BitFilter)
Close #bf.br
bf.accu = 0
bf.bits = 0
bf.offset = 0
End Sub
 
Dim As Integer i
Dim As BitFilter bf
bf.nombre = "test.bin"
 
' for each byte in s, write 7 bits skipping 1
Dim As Byte s(10) => {Asc("a"), Asc("b"), Asc("c"), Asc("d"), _
Asc("e"), Asc("f"), Asc("g"), Asc("h"), Asc("i"), Asc("j"), Asc("k")}
openWriter(bf)
For i = 0 To Ubound(s)
escribe(bf, s(), i, 7, 1)
Next i
closeWriter(bf)
 
' read 7 bits and expand to each byte of s2 skipping 1 bit
openReader(bf)
Dim As Byte s2(0 To Ubound(s)) = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
For i = 0 To Ubound(s2)
lee(bf, s2(), i, 7, 1)
Next i
closeReader(bf)
 
For i = 0 To Ubound(s2)
Print Chr(s2(i));
Next i
Print
 
Sleep</syntaxhighlight>
{{out}}
<pre>abcdefghijk</pre>
 
=={{header|Go}}==
Line 1,347 ⟶ 1,724:
encoder and decoder internal types
(with LZW specific stuff trimmed).
<langsyntaxhighlight Golang="go">// Package bit provides bit-wise IO to an io.Writer and from an io.Reader.
package bit
 
Line 1,549 ⟶ 1,926:
}
return br
}</langsyntaxhighlight>
And a test file (such as <code>bit_test.go</code>):
<langsyntaxhighlight Golang="go">package bit
 
import (
Line 1,615 ⟶ 1,992:
// Written bytes: A9 A3 4F 34 1A 79 A0 C2 83 A6 5E 7D 17 00
// Read back as "This is a test."
}</langsyntaxhighlight>
With this test file, running <code>go test -v</code> will compile the package and run the example verifying the output is as listed above in the <code>// Output:</code> comments.
Additionally, <code>godoc -ex</code> will extract the code comments for documentation and include the examples at the appropriate place
(here the first goes with the <code>WriteBits</code> method and the later with the package documentation).
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
import Data.Char
import Control.Monad
Line 1,650 ⟶ 2,026:
putStrLn $ "Compressed text has " ++ show (length bits `div` 8) ++ " bytes."
putStrLn "Read and decompress:"
putStrLn $ '\t' : bitReader bits</langsyntaxhighlight>
* 7-bits code has lsb leading.
<pre>*Main> :main ["This text is used to illustrate the Rosetta Code task 'bit oriented IO'."]
Line 1,659 ⟶ 2,035:
Read and decompress:
This text is used to illustrate the Rosetta Code task 'bit oriented IO'.</pre>
 
=={{header|J}}==
;Solution
<langsyntaxhighlight lang="j">bitReader =: a. {~ _7 #.\ ({.~ <.&.(%&7)@#)
bitWriter =: , @ ((7$2) & #: @ (a.&i.)), 0 $~ 8 | #</langsyntaxhighlight>
;Usage
Do and undo bit oriented IO:
<langsyntaxhighlight lang="j">text=: 'This text is used to illustrate the Rosetta Code task about ''bit oriented IO''.'
 
bitReader bitWriter text
This text is used to illustrate the Rosetta Code task about 'bit oriented IO'.</langsyntaxhighlight>
Original text length:
<langsyntaxhighlight lang="j"> # text
78</langsyntaxhighlight>
Note: '#' here counts the number of items in its right argument. (In some other languages, # marks the beginning of an in-line comment. J is not one of those languages. Also note that J's command prompt is three spaces. This makes copy&paste easier to use with previously issued commands.)
 
Compressed length:
<langsyntaxhighlight lang="j"> %&8 # bitWriter text
69</langsyntaxhighlight>
Note: this implementation writes the bytes to the session (which is to say, it just gets displayed like any other result. Also, the compressed result is represented as bits - like 1 0 1 0 1... You'll of course need other code when you want to do other things.)
 
=={{header|Julia}}==
ASCII 7-bit character string compression and decompression, to demonstrate bit twiddling. Implemented as generic IO, so that file handles are usable with the same functions.
<syntaxhighlight lang="julia">
<lang Julia>
function compress7(inio, outio)
nextwritebyte = read(inio, UInt8) & 0x7f
Line 1,731 ⟶ 2,105:
println("Compressed to length $(length(outs.data)) on line below:\n", String(outs.data))
println("Decompressed string: ", String(newouts.data))
</langsyntaxhighlight> {{out}} <pre>
Initial string of length 88: These bit oriented I/O functions can be used to implement compressors and decompressors.
Compressed to length 77 on line below:
Line 1,737 ⟶ 2,111:
Decompressed string: These bit oriented I/O functions can be used to implement compressors and decompressors.
</pre>
 
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.2.31
 
import java.io.File
Line 1,823 ⟶ 2,196:
bf.closeReader()
println(String(s2, Charsets.UTF_8))
}</langsyntaxhighlight>
 
{{out}}
Line 1,829 ⟶ 2,202:
abcdefghijk
</pre>
 
=={{header|Lingo}}==
A "BitArray" class can be implemented by sub-classing ByteArray and extending it with methods that allow to get/set individual bits:
<langsyntaxhighlight lang="lingo">-- parent script "BitArray"
 
property ancestor
Line 1,894 ⟶ 2,266:
delete the last char of res
return res
end</langsyntaxhighlight>
 
Simple compression/decompression functions for 7-bit ASCII strings:
<langsyntaxhighlight lang="lingo">----------------------------------------
-- @param {string} str - ASCII string
-- @return {instance} BitArray
Line 1,933 ⟶ 2,305:
end repeat
return str
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">str = "ABC"
ba = crunchASCII(str)
 
Line 1,945 ⟶ 2,317:
 
put decrunchASCII(ba)
-- "ABC"</langsyntaxhighlight>
=={{header|Lua}}==
 
{{works with|Lua|5.1 and later, including LuaJIT}}
 
This code defines two functions that return objects for reading and writing bits from/to strings.
 
<syntaxhighlight lang="lua">local function BitWriter() return {
accumulator = 0, -- For current byte.
bitCount = 0, -- Bits set in current byte.
outChars = {},
 
-- writer:writeBit( bit )
writeBit = function(writer, bit)
writer.bitCount = writer.bitCount + 1
if bit > 0 then
writer.accumulator = writer.accumulator + 2^(8-writer.bitCount)
end
if writer.bitCount == 8 then
writer:_flush()
end
end,
 
-- writer:writeLsb( value, width )
writeLsb = function(writer, value, width)
for i = 1, width do
writer:writeBit(value%2)
value = math.floor(value/2)
end
end,
 
-- dataString = writer:getOutput( )
getOutput = function(writer)
writer:_flush()
return table.concat(writer.outChars)
end,
 
_flush = function(writer)
if writer.bitCount == 0 then return end
 
table.insert(writer.outChars, string.char(writer.accumulator))
writer.accumulator = 0
writer.bitCount = 0
end,
} end
 
local function BitReader(data) return {
bitPosition = 0, -- Absolute position in 'data'.
 
-- bit = reader:readBit( ) -- Returns nil at end-of-data.
readBit = function(reader)
reader.bitPosition = reader.bitPosition + 1
local bytePosition = math.floor((reader.bitPosition-1)/8) + 1
 
local byte = data:byte(bytePosition)
if not byte then return nil end
 
local bitIndex = ((reader.bitPosition-1)%8) + 1
return math.floor(byte / 2^(8-bitIndex)) % 2
end,
 
-- value = reader:readLsb( width ) -- Returns nil at end-of-data.
readLsb = function(reader, width)
local accumulator = 0
 
for i = 1, width do
local bit = reader:readBit()
if not bit then return nil end
 
if bit > 0 then
accumulator = accumulator + 2^(i-1)
end
end
 
return accumulator
end,
} end</syntaxhighlight>
 
Test writing and reading back 7-bit ASCII characters.
 
<syntaxhighlight lang="lua">-- Test writing.
local writer = BitWriter()
local input = "Beautiful moon!"
 
for i = 1, #input do
writer:writeLsb(input:byte(i), 7)
end
 
local data = writer:getOutput() -- May include padding at the end.
 
-- Test reading.
local reader = BitReader(data)
local chars = {}
 
for i = 1, #input do -- Assume the amount of characters is the same as when we wrote the data.
chars[i] = string.char(reader:readLsb(7))
end
 
local output = table.concat(chars)
 
-- Show results.
local hexToBin = {["0"]="0000",["1"]="0001",["2"]="0010",["3"]="0011",
["4"]="0100",["5"]="0101",["6"]="0110",["7"]="0111",
["8"]="1000",["9"]="1001",["a"]="1010",["b"]="1011",
["c"]="1100",["d"]="1101",["e"]="1110",["f"]="1111"}
local function charToHex(c)
return string.format("%02x", c:byte())
end
local function formatBinary(data)
return (data:gsub(".", charToHex)
:gsub(".", hexToBin)
:gsub("........", "%0 "))
end
 
print("In: "..input)
print("Out: "..output)
print("Data: "..formatBinary(data))</syntaxhighlight>
 
{{out}}
 
<pre>
In: Beautiful moon!
Out: Beautiful moon!
Data: 01000011 01001110 00011101 01110010 11110010 11011001 11010111 00110110 00001010 11011111 10111111 01101110 11100001 00000000
</pre>
=={{header|MIPS Assembly}}==
See [[Bitwise IO/MIPS Assembly]]
 
=={{header|Nim}}==
 
<langsyntaxhighlight lang="nim">type
BitWriter * = tuple
file: File
Line 2,047 ⟶ 2,541:
file.close
 
echo "OK"</langsyntaxhighlight>
 
=={{header|OCaml}}==
The [http://code.google.com/p/ocaml-extlib/ extLib] provides [http://ocaml-extlib.googlecode.com/svn/doc/apiref/IO.html#6_BitsAPI bit oriented IO functions].
<langsyntaxhighlight lang="ocaml">let write_7bit_string ~filename ~str =
let oc = open_out filename in
let ob = IO.output_bits(IO.output_channel oc) in
Line 2,057 ⟶ 2,550:
IO.flush_bits ob;
close_out oc;
;;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ocaml">let read_7bit_string ~filename =
let ic = open_in filename in
let ib = IO.input_bits(IO.input_channel ic) in
Line 2,068 ⟶ 2,561:
done; ""
with IO.No_more_input ->
(Buffer.contents buf)</langsyntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang ="perl">#!use /usr/bin/perlstrict;
 
use strict;
 
# $buffer = write_bits(*STDOUT, $buffer, $number, $bits)
sub write_bits :prototype( $$$$ )
{
my ($out, $l, $num, $q) = @_;
Line 2,090 ⟶ 2,580:
 
# flush_bits(*STDOUT, $buffer)
sub flush_bits :prototype( $$ )
{
my ($out, $b) = @_;
Line 2,097 ⟶ 2,587:
 
# ($val, $buf) = read_bits(*STDIN, $buf, $n)
sub read_bits :prototype( $$$ )
{
my ( $in, $b, $n ) = @_;
Line 2,114 ⟶ 2,604:
$b = substr($b, $n);
return ($val, $b);
}</langsyntaxhighlight>
''Crunching'' bytes discarding most significant bit (lossless compression for ASCII and few more!)
<langsyntaxhighlight lang="perl">my $buf = "";
my $c;
while( read(*STDIN, $c, 1) > 0 ) {
$buf = write_bits(*STDOUT, $buf, unpack("C1", $c), 7);
}
flush_bits(*STDOUT, $buf);</langsyntaxhighlight>
Expanding each seven bits to fit a byte (padding the ''eight'' most significant bit with 0):
<langsyntaxhighlight lang="perl">my $buf = "";
my $v;
while(1) {
Line 2,129 ⟶ 2,619:
last if ($buf < 0);
print pack("C1", $v);
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>enum FN, V, BITS -- fields of a bitwiseioreader/writer
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
 
<span style="color: #008080;">enum</span> <span style="color: #000000;">FN</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">V</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">BITS</span> <span style="color: #000080;font-style:italic;">-- fields of a bitwiseioreader/writer</span>
function new_bitwiseio(string filename, mode)
integer fn = open(filename,mode)
<span style="color: #008080;">function</span> <span style="color: #000000;">new_bitwiseio</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">mode</span><span style="color: #0000FF;">)</span>
return {fn,0,0} -- ie {FN,V=0,BITS=0}
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #000000;">mode</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span> <span style="color: #000080;font-style:italic;">-- ie {FN,V=0,BITS=0}</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function new_bitwiseiowriter(string filename)
return new_bitwiseio(filename,"wb")
<span style="color: #008080;">function</span> <span style="color: #000000;">new_bitwiseiowriter</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">new_bitwiseio</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"wb"</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function new_bitwiseioreader(string filename)
return new_bitwiseio(filename,"rb")
<span style="color: #008080;">function</span> <span style="color: #000000;">new_bitwiseioreader</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">new_bitwiseio</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"rb"</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function write_bits(sequence writer, integer v, bits)
integer {fn,wv,wb} = writer,
<span style="color: #008080;">function</span> <span style="color: #000000;">write_bits</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">writer</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">bits</span><span style="color: #0000FF;">)</span>
p2 = power(2,bits), ch
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wv</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wb</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">writer</span><span style="color: #0000FF;">,</span>
if v!=and_bits(v,p2*2-1) then ?9/0 end if
<span style="color: #000000;">p2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">ch</span>
wv = wv*p2+v
<span style="color: #008080;">if</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">!=</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
wb += bits
<span style="color: #000000;">wv</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wv</span><span style="color: #0000FF;">*</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">v</span>
while wb>=8 do
<span style="color: #000000;">wb</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">bits</span>
wb -= 8
<span style="color: #008080;">while</span> <span style="color: #000000;">wb</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">8</span> <span style="color: #008080;">do</span>
p2 = power(2,wb)
<span style="color: #000000;">wb</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">8</span>
ch = floor(wv/p2)
<span style="color: #000000;">p2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wb</span><span style="color: #0000FF;">)</span>
puts(fn,ch)
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">wv</span><span style="color: #0000FF;">/</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">)</span>
wv -= ch*p2
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
end while
<span style="color: #000000;">wv</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">*</span><span style="color: #000000;">p2</span>
if wv>=#100 then ?9/0 end if
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
if wb>=8 then ?9/0 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">wv</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">#100</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
writer[V]= wv
<span style="color: #008080;">if</span> <span style="color: #000000;">wb</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">8</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
writer[BITS]= wb
<span style="color: #000000;">writer</span><span style="color: #0000FF;">[</span><span style="color: #000000;">V</span><span style="color: #0000FF;">]=</span> <span style="color: #000000;">wv</span>
return writer
<span style="color: #000000;">writer</span><span style="color: #0000FF;">[</span><span style="color: #000000;">BITS</span><span style="color: #0000FF;">]=</span> <span style="color: #000000;">wb</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">writer</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function close_bitwiseiowriter(sequence writer)
integer {fn,wv,wb} = writer
<span style="color: #008080;">function</span> <span style="color: #000000;">close_bitwiseiowriter</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">writer</span><span style="color: #0000FF;">)</span>
if wb then
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wv</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wb</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">writer</span>
if wb>=8 then ?9/0 end if -- sanity check
<span style="color: #008080;">if</span> <span style="color: #000000;">wb</span> <span style="color: #008080;">then</span>
writer = write_bits(writer,0,8-wb)
<span style="color: #008080;">if</span> <span style="color: #000000;">wb</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">8</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- sanity check</span>
end if
<span style="color: #000000;">writer</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">write_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">writer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">-</span><span style="color: #000000;">wb</span><span style="color: #0000FF;">)</span>
if writer[V]!=0 then ?9/0 end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if writer[BITS]!=0 then ?9/0 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">writer</span><span style="color: #0000FF;">[</span><span style="color: #000000;">V</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
close(fn)
<span style="color: #008080;">if</span> <span style="color: #000000;">writer</span><span style="color: #0000FF;">[</span><span style="color: #000000;">BITS</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
writer[FN]=-1
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
return writer
<span style="color: #000000;">writer</span><span style="color: #0000FF;">[</span><span style="color: #000000;">FN</span><span style="color: #0000FF;">]=-</span><span style="color: #000000;">1</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">writer</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function read_bits(sequence reader, integer bits)
integer {fn,rv,rb} = reader, ch, p2
<span style="color: #008080;">function</span> <span style="color: #000000;">read_bits</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">reader</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">bits</span><span style="color: #0000FF;">)</span>
while bits>rb do
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rv</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rb</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">reader</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">p2</span>
ch = getc(fn)
<span style="color: #008080;">while</span> <span style="color: #000000;">bits</span><span style="color: #0000FF;">></span><span style="color: #000000;">rb</span> <span style="color: #008080;">do</span>
if ch=-1 then return {-1,reader} end if
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">getc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
rv = rv*#100+ch
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">reader</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
rb += 8
<span style="color: #000000;">rv</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rv</span><span style="color: #0000FF;">*</span><span style="color: #000000;">#100</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ch</span>
end while
<span style="color: #000000;">rb</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">8</span>
rb -= bits
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
p2 = power(2,rb)
<span style="color: #000000;">rb</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">bits</span>
ch = floor(rv/p2)
<span style="color: #000000;">p2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rb</span><span style="color: #0000FF;">)</span>
rv -= ch*p2
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rv</span><span style="color: #0000FF;">/</span><span style="color: #000000;">p2</span><span style="color: #0000FF;">)</span>
reader[V]= rv
<span style="color: #000000;">rv</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">*</span><span style="color: #000000;">p2</span>
reader[BITS]= rb
<span style="color: #000000;">reader</span><span style="color: #0000FF;">[</span><span style="color: #000000;">V</span><span style="color: #0000FF;">]=</span> <span style="color: #000000;">rv</span>
return {ch,reader}
<span style="color: #000000;">reader</span><span style="color: #0000FF;">[</span><span style="color: #000000;">BITS</span><span style="color: #0000FF;">]=</span> <span style="color: #000000;">rb</span>
end function
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">reader</span><span style="color: #0000FF;">}</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function as_hexb(string s, fmt="%02x ")
-- helper funtion, returns hex string, or binary if fmt="%08b "
<span style="color: #008080;">function</span> <span style="color: #000000;">as_hexb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">fmt</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"%02x "</span><span style="color: #0000FF;">)</span>
string res = ""
<span style="color: #000080;font-style:italic;">-- helper funtion, returns hex string, or binary if fmt="%08b "</span>
for i=1 to length(s) do
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
res &= sprintf(fmt,s[i])
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
return trim(res)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
constant test = "This is a test."
--constant test = "This is a test"
<span style="color: #008080;">constant</span> <span style="color: #000000;">test</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"This is a test."</span>
--constant test = "abcdefghijk"
<span style="color: #000080;font-style:italic;">--constant test = "STRINGThis is a test"
--constant test = "This is an ascii string that will be crunched, written, read and expanded.abcdefghijk"
--constant test = "STRING"
printf(1,"\"%s\" as bytes: %s (length %d)\n",{test,as_hexb(test),length(test)})
--constant test = "This is an ascii string that will be crunched, written, read and expanded."</span>
printf(1," original bits: %s\n",{as_hexb(test,"%08b ")})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\"%s\" as bytes: %s (length %d)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">test</span><span style="color: #0000FF;">,</span><span style="color: #000000;">as_hexb</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)})</span>
 
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" original bits: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">as_hexb</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%08b "</span><span style="color: #0000FF;">)})</span>
sequence writer = new_bitwiseiowriter("test.bin")
for i=1 to length(test) do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">writer</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">new_bitwiseiowriter</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.bin"</span><span style="color: #0000FF;">)</span>
writer = write_bits(writer,test[i],7)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">writer</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">write_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">writer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">test</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">7</span><span style="color: #0000FF;">)</span>
writer = close_bitwiseiowriter(writer)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #000000;">writer</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">close_bitwiseiowriter</span><span style="color: #0000FF;">(</span><span style="color: #000000;">writer</span><span style="color: #0000FF;">)</span>
integer fn = open("test.bin","rb")
string bytes = get_text(fn,GT_WHOLE_FILE)
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.bin"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"rb"</span><span style="color: #0000FF;">)</span>
printf(1,"Written bitstream: %s\n",{as_hexb(bytes,"%08b ")})
<span style="color: #004080;">string</span> <span style="color: #000000;">bytes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_WHOLE_FILE</span><span style="color: #0000FF;">)</span>
printf(1,"Written bytes: %s (length %d)\n",{as_hexb(bytes),length(bytes)})
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Written bitstream: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">as_hexb</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bytes</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%08b "</span><span style="color: #0000FF;">)})</span>
close(fn)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Written bytes: %s (length %d)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">as_hexb</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bytes</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bytes</span><span style="color: #0000FF;">)})</span>
 
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
sequence reader = new_bitwiseioreader("test.bin")
bytes = ""
<span style="color: #004080;">sequence</span> <span style="color: #000000;">reader</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">new_bitwiseioreader</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"test.bin"</span><span style="color: #0000FF;">)</span>
integer ch
<span style="color: #000000;">bytes</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
while true do
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span>
{ch,reader} = read_bits(reader,7)
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
if ch=-1 then exit end if
<span style="color: #0000FF;">{</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">reader</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">read_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">reader</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">)</span>
bytes &= ch
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #000000;">bytes</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">ch</span>
printf(1,"\"%s\" as bytes: %s (length %d)\n",{bytes,as_hexb(bytes),length(bytes)})</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\"%s\" as bytes: %s (length %d)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">bytes</span><span style="color: #0000FF;">,</span><span style="color: #000000;">as_hexb</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bytes</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bytes</span><span style="color: #0000FF;">)})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,247 ⟶ 2,740:
simply ignore retrieved zero bytes, but that could fairly obviously create problems for some forms of binary data. A better solution
might be for the data to embed or prefix it's own length. The other four (commented-out) test values do not exhibit this problem.
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de write7bitwise (Lst)
(let (Bits 0 Byte)
(for N Lst
Line 2,270 ⟶ 2,762:
(setq Byte (& 127 (>> (- Bits 7) N))) ) )
(when (= 7 Bits)
(link Byte) ) ) ) )</langsyntaxhighlight>
<langsyntaxhighlight PicoLisplang="picolisp">(out 'a (write7bitwise (127 0 127 0 127 0 127 0 127)))
(hd 'a)
(in 'a (println (read7bitwise)))
Line 2,281 ⟶ 2,773:
(out 'a (write7bitwise (mapcar char (chop "STRING"))))
(hd 'a)
(println (mapcar char (in 'a (read7bitwise))))</langsyntaxhighlight>
{{out}}
<pre>00000000 FE 03 F8 0F E0 3F 80 FE .....?..
Line 2,289 ⟶ 2,781:
00000000 A7 52 94 99 D1 C0 .R....
("S" "T" "R" "I" "N" "G")</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">declare onebit bit(1) aligned, bs bit (1000) varying aligned;
on endfile (sysin) go to ending;
bs = ''b;
Line 2,301 ⟶ 2,792:
bs = bs || copy('0'b, mod(length(bs), 8) );
/* pad length to a multiple of 8 */
put edit (bs) (b);</langsyntaxhighlight>
Example:
<pre>
Line 2,333 ⟶ 2,824:
1010011101010010100101001001100111010001111010011000110100010100000000
</pre>
 
=={{header|PureBasic}}==
The bits are read/written with the HSB being read/written first, then each full byte (8 bits) is read/written in succession. Depending on the native integer size the compiler is using, upto 32-bits or 64-bits can be read/written at once. The procedure flushBits() should be called when the reading/writing of bits is completed. If a partial byte is written the bits containing data will begin with the HSB and the padding bits will end with the LSB.
 
As a slight speed modification, the readBits() and writeBits() procedures will attempt to write groups of bits whenever possible.
<langsyntaxhighlight PureBasiclang="purebasic">Structure fileDataBits
bitsToWrite.i
bitsToRead.i
Line 2,457 ⟶ 2,947:
result + "Expanded string = '" + testReadString + "'"
 
MessageRequester("Results", result)</langsyntaxhighlight>
{{out}}
<pre>Original ascii string is 74 bytes.
Line 2,463 ⟶ 2,953:
The expanded string is the same as the original.
Expanded string = 'This is an ascii string that will be crunched, written, read and expanded.'</pre>
 
=={{header|Python}}==
This following code works in both Python 2 & 3. Suggested module file name <tt>bitio.py</tt>.
<langsyntaxhighlight lang="python">class BitWriter(object):
def __init__(self, f):
self.accumulator = 0
Line 2,555 ⟶ 3,044:
chars.append(chr(x))
print(''.join(chars))
</syntaxhighlight>
</lang>
Another usage example showing how to "crunch" an 8-bit byte ASCII stream discarding the most significant "unused" bit...and read it back.
<langsyntaxhighlight lang="python">import sys
import bitio
 
Line 2,566 ⟶ 3,055:
c = sys.stdin.read(1)
o.flush()
</syntaxhighlight>
</lang>
...and to "decrunch" the same stream:
<langsyntaxhighlight lang="python">import sys
import bitio
 
Line 2,576 ⟶ 3,065:
if not r.read: # nothing read
break
sys.stdout.write(chr(x))</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,640 ⟶ 3,128:
(printf "Decrunched string ~aequal to original.\n"
(if (equal? orig (decrunch "crunched.out")) "" "NOT "))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,646 ⟶ 3,134:
Decrunched string equal to original.
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub encode-ascii(Str $s) {
my @b = flat $s.ords».fmt("%07b")».comb;
@b.push(0) until @b %% 8; # padding
Line 2,662 ⟶ 3,149:
}
say my $encode = encode-ascii 'STRING';
say decode-ascii $encode;</langsyntaxhighlight>
{{out}}
<pre>Buf:0x<03 8b 99 29 4a e5>
STRING</pre>
 
=={{header|Red}}==
<langsyntaxhighlight lang="red">Red [
Title: "Bitwise IO"
Link: http://rosettacode.org/wiki/Bitwise_IO
Line 2,726 ⟶ 3,212:
pad "Expanded (string): " 20 mold to-string expanded
]
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,740 ⟶ 3,226:
Expanded (string): "Red forever!"
</pre>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ****************************************************************
* 01.11.2012 Walter Pachl
***********************************************************************/
Line 2,768 ⟶ 3,253:
r=r||x2c(x) /* convert to character */
End /* and append to result */
Say 'r='r /* show result */</langsyntaxhighlight>
{{out}}
<pre>
Line 2,778 ⟶ 3,263:
 
===version 2===
<langsyntaxhighlight lang="rexx">/*REXX pgm encodes/decodes/displays ASCII character strings as (7─bits) binary string.*/
parse arg $; if $=='' then $= 'STRING' /*get optional argument; Use default ? */
say ' input string=' $ /*display the input string to terminal.*/
Line 2,791 ⟶ 3,276:
dcomp: parse arg x; z=; do k=1 by 7 to length(x); _= substr(x, k, 7)
if right(_, 1)==' ' then leave; z= z || x2c( b2x(0 || _) )
end /*k*/; return z</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 2,798 ⟶ 3,283:
decoded string= STRING
</pre>
 
=={{header|Ruby}}==
{{trans|Tcl}}
{{works with|Ruby|1.8.7}}
<langsyntaxhighlight lang="ruby">def crunch(ascii)
bitstring = ascii.bytes.collect {|b| "%07b" % b}.join
[bitstring].pack("B*")
Line 2,836 ⟶ 3,320:
else
puts "fail!"
end</langsyntaxhighlight>
 
=={{header|Rust}}==
The implementation accepts the number of bits to discard/expand as an argument.
 
<langsyntaxhighlight Rustlang="rust">pub trait Codec<Input = u8> {
type Output: Iterator<Item = u8>;
 
Line 3,001 ⟶ 3,484:
let decompressed = process_bytes(BitExpand::new(discard), &compressed);
print_bytes(&decompressed);
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
The Seed7 library [httphttps://seed7.sourceforge.net/libraries/bitdata.htm bitdata.s7i] defines
several functions to do bitwise I/O. Bitwise data can be read from (or written to) a string or a file.
The direction of bits can be from LSB (least significant bit) to MSB (most significant bit) or vice versa.
In the program below the functions
[httphttps://seed7.sourceforge.net/libraries/bitdata.htm#putBitsMsb(inout_file,inout_integer,in_var_integer,in_var_integer) putBitsMsb], [https://seed7.sourceforge.net/libraries/bitdata.htm#openMsbBitStream(in_file) openMsbBitStream] and [httphttps://seed7.sourceforge.net/libraries/bitdata.htm#getBitsMsbgetBits(inout_fileinout_msbBitStream,inout_integer,in_var_integerin_integer) getBitsMsbgetBits] are used.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bitdata.s7i";
include "strifile.s7i";
Line 3,035 ⟶ 3,517:
const proc: finishWriteAscii (inout file: outFile, inout integer: bitPos) is func
begin
putBitsMsb(outFile, bitPos, 0, 7); # Write a terminating NUL char.
write(outFile, chr(ord(outFile.bufferChar)));
end func;
 
const procfunc string: initReadAsciireadAscii (inout file: outFile, inout integermsbBitStream: bitPosaBitStream) is func
begin
bitPos := 8;
end func;
 
const func string: readAscii (inout file: inFile, inout integer: bitPos, in integer: length) is func
result
var string: stri is "";
Line 3,049 ⟶ 3,527:
var char: ch is ' ';
begin
while not eof(inFile) and length(stri)ch <> length'\0;' do
ch := chr(getBitsMsbgetBits(inFile, bitPosaBitStream, 7));
if inFile.bufferCharch <> EOF'\0;' then
stri &:= ch;
end if;
Line 3,061 ⟶ 3,539:
var file: aFile is STD_NULL;
var integer: bitPos is 0;
var msbBitStream: aBitStream is msbBitStream.value;
begin
aFile := openStrifileopenStriFile;
initWriteAscii(aFile, bitPos);
writeAscii(aFile, bitPos, "Hello, Rosetta Code!");
finishWriteAscii(aFile, bitPos);
seek(aFile, 1);
initReadAsciiaBitStream := openMsbBitStream(aFile, bitPos);
writeln(literal(readAscii(aFile, bitPos, 100aBitStream)));
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,077 ⟶ 3,556:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc crunch {ascii} {
Line 3,124 ⟶ 3,603:
} else {
error "not the same"
}</langsyntaxhighlight>
{{out}}
<pre>my ascii string is 74 bytes
the file containing the crunched text is 65 bytes
the expanded string is the same as the original</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
 
class BitFilter {
Line 3,231 ⟶ 3,709:
for (i in 0...s2.count) bf.read(s2, i, 7, 1)
bf.closeReader()
System.print(s2.map { |b| String.fromByte(b) }.join())</langsyntaxhighlight>
 
{{out}}
Line 3,238 ⟶ 3,716:
</pre>
 
=={{header|Z80 Assembly}}==
 
===Uncompressing Packed Bytes into ASCII Zeroes and Ones===
Code is optimized to use what I call a "revolving bit mask" since there is no way to iterate through <code>BIT</code> commands without self-modifying code which is even more difficult to read in my opinion. Using <code>BIT</code> tests without self-modifying code would require the loop to be unrolled.
<syntaxhighlight lang="z80">StoreBinaryString:
;INPUT:
; HL = SOURCE ADDRESS
; DE = OUTPUT STRING RAM
; BC = HOW MANY BYTES OF SOURCE DATA TO CONVERT
ld a,(hl)
push bc
ld b,a ;backup a for later
ld c,%10000000 ;a "revolving bit mask" is used to compare
; each bit of A, in sequence.
loop:
ld a,b ;restore A
and c
ld a,'0' ;get ascii 0 into A. This does not affect the flags!
jr z,skip ;this jump is based on the result of B AND C
inc a ;convert ascii 0 into ascii 1, only if B AND C was nonzero.
skip:
LD (DE),A ;store in output string
inc de ;next byte of output string
rrc c ;shift the bit mask down to the next bit of A
jr nc,loop ;once a 1 is shifted into the carry, we're finished. Otherwise, check next bit.
pop bc
inc hl
dec bc
ld a,b
or c
jp nz,StoreBinaryString
ret</syntaxhighlight>
{{out}}
<pre>
Hexdump (using &57 &50 as input):
 
30 31 30 31 30 31 31 31 01010111
30 31 30 31 30 30 30 30 01010000
</pre>
 
===Compressing a String of ASCII Zeroes and Ones===
<syntaxhighlight lang="z80">CompressBinaryStrings_7bit:
; HL = pointer to output
; DE = pointer to input. Input is assumed to equal &30 or &31
; Usage:
; LD hl,OutputRam
; LD de,InputRam
; CALL CompressBinaryStrings_7bit
; If the string "runs out" before the 8 bit boundary, the rest are rotated into place.
; e.g. input = "0101" then the procedure will RLC until those bits
; are as far left as possible.
 
outerloop:
inc de ;skip bit 7
ld b,7 ;loop counter
innerloop:
ld a,(de)
or a ;compares accumulator to zero. Assumes a null-terminated string.
; Otherwise compare A to your terminator of choice.
 
jr z,HandleEarlyExit
;input is assumed to be &30 or &31, so the least significant bit tells us
; all we need to know. The rest of the byte can be discarded.
 
rra ;rotate the result into the carry
rl (hl) ;rotate it out of the carry into (HL)
inc de
z_djnz innerloop
;a macro that becomes DJNZ <label> on Zilog Z80 and DEC B JR NZ,<label> on Sharp LR35902
 
inc hl ;next output byte
jp outerloop
HandleEarlyExit:
xor a ;LD A,0
cp b ;compare B to zero
ret z ;if B=0, we're done. No need to adjust the last byte
loop_earlyExit
rlc (hl)
z_djnz loop_earlyExit
ret</syntaxhighlight>
 
{{out}}
<pre>
(Tested using input string of "0101011101010". Printing routines left out for brevity but can be added upon request.
 
57 50
</pre>
=={{header|zkl}}==
This code implements two state machines: one that transforms a bit stream (ie a stream of ints with a maximum number of bits) to a byte stream and one does the reverse transform. All streams are considered infinite (eg a file or socket).
 
Bits to bytes:
<langsyntaxhighlight lang="zkl"> // stream of numBits sized ints to bytes, numBits<8
fcn toBytes(n,[(numBits,acc,bitsSoFar)]state){
acc=acc.shiftLeft(numBits) + n; bitsSoFar+=numBits;
Line 3,254 ⟶ 3,822:
state.clear(numBits,acc,bitsSoFar);
r
}</langsyntaxhighlight>
Encode a stream of 6 bit characters:
<langsyntaxhighlight lang="zkl">ns:="THIS IS A TEST".pump(List,"toAsc",'-(0x20));
ns.println(ns.len());
 
Line 3,262 ⟶ 3,830:
cns:=ns.pump(List,toBytes.fp1(state)); // List could be a file or socket or ...
if(state[2]) cns+=toBytes(0,state); // flush
cns.println(cns.len());</langsyntaxhighlight>
{{out}}
<pre>
Line 3,269 ⟶ 3,837:
</pre>
Byte stream to bit stream:
<langsyntaxhighlight lang="zkl"> // stream of bytes to numBits sized ints, 1<numBits<32
fcn fromBytes(n,[(numBits,acc,bitsSoFar,buf)]state){
acc=acc.shiftLeft(8) + n; bitsSoFar+=8;
Line 3,280 ⟶ 3,848:
state.clear(numBits,acc,bitsSoFar,buf);
return(Void.Write,Void.Write,buf); // append contents of buf to result
}</langsyntaxhighlight>
Decode the above stream:
<langsyntaxhighlight lang="zkl">state:=L(6,0,0,L()); // output is six bits wide
r:=cns.pump(List,fromBytes.fp1(state)); // cns could be a file or ...
r.println(r.len());
r.pump(String,'+(0x20),"toChar").println();</langsyntaxhighlight>
{{out}}
<pre>
Line 3,291 ⟶ 3,859:
THIS IS A TEST
</pre>
 
{{omit from|AWK|Traditional AWK has no bitwise operators}}
{{omit from|gnuplot}}
29

edits