Bitwise IO: Difference between revisions

Replace deprecated functions
m (syntax highlighting fixup automation)
(Replace deprecated functions)
 
(10 intermediate revisions by 7 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 25:
{{trans|Python}}
 
<syntaxhighlight lang="11l">T BitWriter
FileFileWr out
accumulator = 0
bcount = 0
 
F (fname)
.out = File(fname, ‘w’WRITE)
 
F _writebit(bit)
Line 61:
 
F (fname)
.input = File(fname, ‘r’)
 
F _readbit()
I .bcount == 0
V a = .input.read_bytes(at_most' 1)
I !a.empty
.accumulator = a[0]
Line 105:
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.
<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.
Line 154:
===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
Line 249:
1400: 57 50
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Streams; use Ada.Streams;
with Ada.Finalization;
 
Line 272 ⟶ 271:
end Bit_Streams;</syntaxhighlight>
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:
<syntaxhighlight lang="ada">package body Bit_Streams is
procedure Finalize (Stream : in out Bit_Stream) is
begin
Line 306 ⟶ 305:
end Bit_Streams;</syntaxhighlight>
Example of use:
<syntaxhighlight lang="ada">with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with Bit_Streams; use Bit_Streams;
 
Line 339 ⟶ 338:
end if;
end Test_Bit_Streams;</syntaxhighlight>
 
=={{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]}}
<syntaxhighlight lang="algol68"># NIBBLEs are of any width, eg 1-bit OR 4-bits etc. #
MODE NIBBLE = STRUCT(INT width, BITS bits);
 
Line 492 ⟶ 490:
STRING & ABACUS => 101001110101001010010100100110011101000111010000001001100100000100000110000101000001100001110101011010011
</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">file = %A_WorkingDir%\z.dat
IfExist, %A_WorkingDir%\z.dat
FileDelete %file%
Line 620 ⟶ 617:
Return TotalRead
}</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> file$ = @tmp$ + "bitwise.tmp"
test$ = "Hello, world!"
Line 670 ⟶ 666:
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.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 789 ⟶ 790:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.IO;
 
Line 934 ⟶ 935:
}
}</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang="lisp">
(defpackage :rosetta.bitwise-i/o
(:use :common-lisp)
Line 1,083:
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="lisp">
BITWISE-I/O> (bitwise-i/o-demo)
 
Line 1,111:
⇒ ABORT
</syntaxhighlight>
 
=={{header|D}}==
{{trans|C}}
<syntaxhighlight lang="d">import std.stdio: File;
import core.stdc.stdio: FILE, fputc, fgetc;
import std.string: representation;
Line 1,253 ⟶ 1,252:
{{libheader| System.Classes}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi"delphi">
program Bitwise_IO;
 
Line 1,429 ⟶ 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}}==
<syntaxhighlight lang="erlang">-module(bitwise_io).
-compile([export_all]).
 
Line 1,485 ⟶ 1,567:
io:format("~p~n",[Decompressed]).</syntaxhighlight>
{{out}}
<syntaxhighlight 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,493 ⟶ 1,575:
185> bitwise_io:test_file_io().
<<"Hello, Rosetta Code!">></syntaxhighlight>
 
=={{header|Forth}}==
The stream status is kept on the stack ( b m ), where b is the character accumulator
Line 1,499 ⟶ 1,580:
with the MSB. (The writing code was originally used for Mandelbrot generation.)
 
<syntaxhighlight lang="forth">\ writing
 
: init-write ( -- b m ) 0 128 ;
Line 1,520 ⟶ 1,601:
dup 0= if 2drop init-read then
2dup and swap 2/ swap ;</syntaxhighlight>
 
=={{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,526 ⟶ 1,724:
encoder and decoder internal types
(with LZW specific stuff trimmed).
<syntaxhighlight lang=Go"go">// Package bit provides bit-wise IO to an io.Writer and from an io.Reader.
package bit
 
Line 1,730 ⟶ 1,928:
}</syntaxhighlight>
And a test file (such as <code>bit_test.go</code>):
<syntaxhighlight lang=Go"go">package bit
 
import (
Line 1,798 ⟶ 1,996:
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}}==
<syntaxhighlight lang="haskell">import Data.List
import Data.Char
import Control.Monad
Line 1,838 ⟶ 2,035:
Read and decompress:
This text is used to illustrate the Rosetta Code task 'bit oriented IO'.</pre>
 
=={{header|J}}==
;Solution
<syntaxhighlight lang="j">bitReader =: a. {~ _7 #.\ ({.~ <.&.(%&7)@#)
bitWriter =: , @ ((7$2) & #: @ (a.&i.)), 0 $~ 8 | #</syntaxhighlight>
;Usage
Do and undo bit oriented IO:
<syntaxhighlight 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'.</syntaxhighlight>
Original text length:
<syntaxhighlight lang="j"> # text
78</syntaxhighlight>
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:
<syntaxhighlight lang="j"> %&8 # bitWriter text
69</syntaxhighlight>
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"julia">
function compress7(inio, outio)
nextwritebyte = read(inio, UInt8) & 0x7f
Line 1,916 ⟶ 2,111:
Decompressed string: These bit oriented I/O functions can be used to implement compressors and decompressors.
</pre>
 
=={{header|Kotlin}}==
{{trans|C}}
<syntaxhighlight lang="scala">// version 1.2.31
 
import java.io.File
Line 2,008 ⟶ 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:
<syntaxhighlight lang="lingo">-- parent script "BitArray"
 
property ancestor
Line 2,076 ⟶ 2,269:
 
Simple compression/decompression functions for 7-bit ASCII strings:
<syntaxhighlight lang="lingo">----------------------------------------
-- @param {string} str - ASCII string
-- @return {instance} BitArray
Line 2,114 ⟶ 2,307:
end</syntaxhighlight>
 
<syntaxhighlight lang="lingo">str = "ABC"
ba = crunchASCII(str)
 
Line 2,125 ⟶ 2,318:
put decrunchASCII(ba)
-- "ABC"</syntaxhighlight>
 
=={{header|Lua}}==
 
Line 2,132 ⟶ 2,324:
This code defines two functions that return objects for reading and writing bits from/to strings.
 
<syntaxhighlight lang=Lua"lua">local function BitWriter() return {
accumulator = 0, -- For current byte.
bitCount = 0, -- Bits set in current byte.
Line 2,205 ⟶ 2,397:
Test writing and reading back 7-bit ASCII characters.
 
<syntaxhighlight lang=Lua"lua">-- Test writing.
local writer = BitWriter()
local input = "Beautiful moon!"
Line 2,250 ⟶ 2,442:
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}}==
 
<syntaxhighlight lang="nim">type
BitWriter * = tuple
file: File
Line 2,352 ⟶ 2,542:
 
echo "OK"</syntaxhighlight>
 
=={{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].
<syntaxhighlight 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,363 ⟶ 2,552:
;;</syntaxhighlight>
 
<syntaxhighlight 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,373 ⟶ 2,562:
with IO.No_more_input ->
(Buffer.contents buf)</syntaxhighlight>
 
=={{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,394 ⟶ 2,580:
 
# flush_bits(*STDOUT, $buffer)
sub flush_bits :prototype( $$ )
{
my ($out, $b) = @_;
Line 2,401 ⟶ 2,587:
 
# ($val, $buf) = read_bits(*STDIN, $buf, $n)
sub read_bits :prototype( $$$ )
{
my ( $in, $b, $n ) = @_;
Line 2,420 ⟶ 2,606:
}</syntaxhighlight>
''Crunching'' bytes discarding most significant bit (lossless compression for ASCII and few more!)
<syntaxhighlight lang="perl">my $buf = "";
my $c;
while( read(*STDIN, $c, 1) > 0 ) {
Line 2,427 ⟶ 2,613:
flush_bits(*STDOUT, $buf);</syntaxhighlight>
Expanding each seven bits to fit a byte (padding the ''eight'' most significant bit with 0):
<syntaxhighlight lang="perl">my $buf = "";
my $v;
while(1) {
Line 2,436 ⟶ 2,622:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"phix">(notonline)-->
<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>
Line 2,554 ⟶ 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}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de write7bitwise (Lst)
(let (Bits 0 Byte)
(for N Lst
Line 2,578 ⟶ 2,763:
(when (= 7 Bits)
(link Byte) ) ) ) )</syntaxhighlight>
<syntaxhighlight lang=PicoLisp"picolisp">(out 'a (write7bitwise (127 0 127 0 127 0 127 0 127)))
(hd 'a)
(in 'a (println (read7bitwise)))
Line 2,596 ⟶ 2,781:
00000000 A7 52 94 99 D1 C0 .R....
("S" "T" "R" "I" "N" "G")</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang=PL"pl/Ii">declare onebit bit(1) aligned, bs bit (1000) varying aligned;
on endfile (sysin) go to ending;
bs = ''b;
Line 2,640 ⟶ 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.
<syntaxhighlight lang=PureBasic"purebasic">Structure fileDataBits
bitsToWrite.i
bitsToRead.i
Line 2,770 ⟶ 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>.
<syntaxhighlight lang="python">class BitWriter(object):
def __init__(self, f):
self.accumulator = 0
Line 2,864 ⟶ 3,046:
</syntaxhighlight>
Another usage example showing how to "crunch" an 8-bit byte ASCII stream discarding the most significant "unused" bit...and read it back.
<syntaxhighlight lang="python">import sys
import bitio
 
Line 2,875 ⟶ 3,057:
</syntaxhighlight>
...and to "decrunch" the same stream:
<syntaxhighlight lang="python">import sys
import bitio
 
Line 2,884 ⟶ 3,066:
break
sys.stdout.write(chr(x))</syntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
#lang racket
 
Line 2,953 ⟶ 3,134:
Decrunched string equal to original.
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub encode-ascii(Str $s) {
my @b = flat $s.ords».fmt("%07b")».comb;
@b.push(0) until @b %% 8; # padding
Line 2,973 ⟶ 3,153:
<pre>Buf:0x<03 8b 99 29 4a e5>
STRING</pre>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red [
Title: "Bitwise IO"
Link: http://rosettacode.org/wiki/Bitwise_IO
Line 3,047 ⟶ 3,226:
Expanded (string): "Red forever!"
</pre>
 
=={{header|REXX}}==
===version 1===
<syntaxhighlight lang="rexx">/* REXX ****************************************************************
* 01.11.2012 Walter Pachl
***********************************************************************/
Line 3,085 ⟶ 3,263:
 
===version 2===
<syntaxhighlight 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 3,105 ⟶ 3,283:
decoded string= STRING
</pre>
 
=={{header|Ruby}}==
{{trans|Tcl}}
{{works with|Ruby|1.8.7}}
<syntaxhighlight lang="ruby">def crunch(ascii)
bitstring = ascii.bytes.collect {|b| "%07b" % b}.join
[bitstring].pack("B*")
Line 3,144 ⟶ 3,321:
puts "fail!"
end</syntaxhighlight>
 
=={{header|Rust}}==
The implementation accepts the number of bits to discard/expand as an argument.
 
<syntaxhighlight lang=Rust"rust">pub trait Codec<Input = u8> {
type Output: Iterator<Item = u8>;
 
Line 3,309 ⟶ 3,485:
print_bytes(&decompressed);
}</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bitdata.s7i";
include "strifile.s7i";
Line 3,342 ⟶ 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,356 ⟶ 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,368 ⟶ 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;</syntaxhighlight>
 
Line 3,384 ⟶ 3,556:
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">package require Tcl 8.5
 
proc crunch {ascii} {
Line 3,436 ⟶ 3,608:
the file containing the crunched text is 65 bytes
the expanded string is the same as the original</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang=ecmascript"wren">import "io" for File
 
class BitFilter {
Line 3,549 ⟶ 3,720:
===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
Line 3,587 ⟶ 3,758:
 
===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
Line 3,635 ⟶ 3,806:
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:
<syntaxhighlight 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,654 ⟶ 3,824:
}</syntaxhighlight>
Encode a stream of 6 bit characters:
<syntaxhighlight lang="zkl">ns:="THIS IS A TEST".pump(List,"toAsc",'-(0x20));
ns.println(ns.len());
 
Line 3,667 ⟶ 3,837:
</pre>
Byte stream to bit stream:
<syntaxhighlight 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,680 ⟶ 3,850:
}</syntaxhighlight>
Decode the above stream:
<syntaxhighlight 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());
Line 3,689 ⟶ 3,859:
THIS IS A TEST
</pre>
 
{{omit from|AWK|Traditional AWK has no bitwise operators}}
{{omit from|gnuplot}}
29

edits