Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Bitwise_operations
note: Discrete math

View file

@ -0,0 +1,9 @@
{{basic data operation}}
;Task:
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
If any operation is not available in your language, note it.
<br><br>

View file

@ -0,0 +1,12 @@
V x = 10
V y = 2
print(x = x)
print(y = y)
print(NOT x = (-)x)
print(x AND y = (x [&] y))
print(x OR y = (x [|] y))
print(x XOR y = (x (+) y))
print(x SHL y = (x << y))
print(x SHR y = (x >> y))
print(x ROL y = rotl(x, y))
print(x ROR y = rotr(x, y))

View file

@ -0,0 +1,82 @@
* Bitwise operations 15/02/2017
BITWISE CSECT
USING BITWISE,R13
B 72(R15)
DC 17F'0'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
L R1,A
XDECO R1,PG
MVC OP,=CL7'A='
XPRNT OP,L'OP+L'PG
L R1,B
XDECO R1,PG
MVC OP,=CL7'B='
XPRNT OP,L'OP+L'PG
* And
L R1,A
N R1,B
XDECO R1,PG
MVC OP,=C'A AND B'
XPRNT OP,L'OP+L'PG
* Or
L R1,A
O R1,B
XDECO R1,PG
MVC OP,=C'A OR B'
XPRNT OP,L'OP+L'PG
* Xor
L R1,A
X R1,B
XDECO R1,PG
MVC OP,=C'A XOR B'
XPRNT OP,L'OP+L'PG
* Not
L R1,A
X R1,=X'FFFFFFFF' not (by xor -1)
XDECO R1,PG
MVC OP,=CL7'NOT A'
XPRNT OP,L'OP+L'PG
*
MVC A,=X'80000008' a=-2147483640 (-2^31+8)
L R1,A
XDECO R1,PG
MVC OP,=CL7'A='
XPRNT OP,L'OP+L'PG
* shift right arithmetic (on 31 bits)
L R1,A
SRA R1,3
XDECO R1,PG
MVC OP,=C'A SRA 3'
XPRNT OP,L'OP+L'PG
* shift left arithmetic (on 31 bits)
L R1,A
SLA R1,3
XDECO R1,PG
MVC OP,=C'A SLA 3'
XPRNT OP,L'OP+L'PG
* shift right logical (on 32 bits)
L R1,A
SRL R1,3
XDECO R1,PG
MVC OP,=C'A SRL 3'
XPRNT OP,L'OP+L'PG
* shift left logical (on 32 bits)
L R1,A
SLL R1,3
XDECO R1,PG
MVC OP,=C'A SLL 3'
XPRNT OP,L'OP+L'PG
*
RETURN L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
A DC F'21'
B DC F'3'
OP DS CL7
PG DS CL12
YREGS
END BITWISE

View file

@ -0,0 +1,2 @@
LDA #$05
STA temp ;temp equals 5 for the following

View file

@ -0,0 +1,2 @@
LDA #$08
AND temp

View file

@ -0,0 +1,2 @@
LDA #$08
ORA temp

View file

@ -0,0 +1,2 @@
LDA #$08
EOR temp

View file

@ -0,0 +1,2 @@
LDA #$08
EOR #255

View file

@ -0,0 +1,6 @@
LDA #$FF
CLC ;clear the carry. That way, ROR will not accidentally shift a 1 into the top bit of a positive number
BPL SKIP
SEC ;if the value in A is negative, setting the carry will ensure that ROR will insert a 1 into bit 7 of A upon rotating.
SKIP:
ROR

View file

@ -0,0 +1,2 @@
LDA #$01
ROL ;if the carry was set prior to the ROL, A = 3. If the carry was clear, A = 2.

View file

@ -0,0 +1,2 @@
LDA #$01
ROR ;if the carry was set prior to the ROR, A = 0x80. If clear, A = 0.

View file

@ -0,0 +1,3 @@
MOVE.W #$100,D0
MOVE.W #$200,D1
AND.W D0,D1

View file

@ -0,0 +1,3 @@
MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXL.W D1,D0

View file

@ -0,0 +1,3 @@
MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXR.W D1,D0

View file

@ -0,0 +1,3 @@
MOVE.W #$100,D0
MOVE.W #$200,D1
OR.W D0,D1

View file

@ -0,0 +1,3 @@
MOVE.W #$100,D0
MOVE.W #$200,D1
EOR.W D0,D1

View file

@ -0,0 +1,2 @@
MOVE.W #$100,D0
NOT.W D0

View file

@ -0,0 +1,3 @@
MOVE.W #$FF,D0
MOVE.W #$04,D1
LSL.W D1,D0 ;shifts 0x00FF left 4 bits

View file

@ -0,0 +1,3 @@
MOVE.W #$FF,D0
MOVE.W #$04,D1
LSR.W D1,D0 ;shifts 0x00FF right 4 bits

View file

@ -0,0 +1,3 @@
MOVE.W #$FF00,D0
MOVE.W #$04,D1
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign

View file

@ -0,0 +1,3 @@
MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROL.W D1,D0

View file

@ -0,0 +1,3 @@
MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROR.W D1,D0

View file

@ -0,0 +1,52 @@
; bitwise AND
anl a, b
; bitwise OR
orl a, b
; bitwise XOR
xrl a, b
; bitwise NOT
cpl a
; left shift
inc b
rrc a
loop:
rlc a
clr c
djnz b, loop
; right shift
inc b
rlc a
loop:
rrc a
clr c
djnz b, loop
; arithmetic right shift
push 20
inc b
rlc a
mov 20.0, c
loop:
rrc a
mov c, 20.0
djnz b, loop
pop 20
; left rotate
inc b
rr a
loop:
rl a
djnz b, loop
; right rotate
inc b
rl a
loop:
rr a
djnz b, loop

View file

@ -0,0 +1,3 @@
MOV AX,0345h
MOV BX,0444h
AND AX,BX

View file

@ -0,0 +1,3 @@
MOV AX,03h
MOV CL,02h
RCL AX,CL

View file

@ -0,0 +1,3 @@
MOV AX,03h
MOV CL,02h
RCR AX,CL

View file

@ -0,0 +1,3 @@
MOV AX,0345h
MOV BX,0444h
OR AX,BX

View file

@ -0,0 +1,3 @@
MOV AX,0345h
MOV BX,0444h
XOR AX,BX

View file

@ -0,0 +1,2 @@
MOV AX,0345h
NOT AX

View file

@ -0,0 +1,3 @@
MOV AX,03h
MOV CL,02h
SHL AX,CL

View file

@ -0,0 +1,3 @@
MOV AX,03h
MOV CL,02h
SHR AX,CL

View file

@ -0,0 +1,3 @@
MOV AX,03h
MOV CL,02h
SAR AX,CL

View file

@ -0,0 +1,3 @@
MOV AX,03h
MOV CL,02h
ROL AX,CL

View file

@ -0,0 +1,3 @@
MOV AX,03h
MOV CL,02h
ROR AX,CL

View file

@ -0,0 +1,145 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program bitwise64.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/************************************/
/* Initialized data */
/************************************/
.data
szMessResultAnd: .asciz "Result of And : \n"
szMessResultOr: .asciz "Result of Or : \n"
szMessResultEor: .asciz "Result of Exclusif Or : \n"
szMessResultNot: .asciz "Result of Not : \n"
szMessResultLsl: .asciz "Result of left shift : \n"
szMessResultLsr: .asciz "Result of right shift : \n"
szMessResultAsr: .asciz "Result of Arithmetic right shift : \n"
szMessResultRor: .asciz "Result of rotate right : \n"
szMessResultClear: .asciz "Result of Bit Clear : \n"
sMessAffBin: .ascii "Register: "
sZoneBin: .space 65,' '
.asciz "\n"
/************************************/
/* code section */
/************************************/
.text
.global main
main:
ldr x0,qAdrszMessResultAnd
bl affichageMess
mov x0,#5
and x0,x0,#15
bl affichage2
ldr x0,qAdrszMessResultOr
bl affichageMess
mov x0,#5
orr x0,x0,#15
bl affichage2
ldr x0,qAdrszMessResultEor
bl affichageMess
mov x0,#5
eor x0,x0,#15
bl affichage2
ldr x0,qAdrszMessResultNot
bl affichageMess
mov x0,#5
mvn x0,x0
bl affichage2
ldr x0,qAdrszMessResultLsl
bl affichageMess
mov x0,#5
lsl x0,x0,#1
bl affichage2
ldr x0,qAdrszMessResultLsr
bl affichageMess
mov x0,#5
lsr x0,x0,#1
bl affichage2
ldr x0,qAdrszMessResultAsr
bl affichageMess
mov x0,#-5
bl affichage2
mov x0,#-5
asr x0,x0,#1
bl affichage2
ldr x0,qAdrszMessResultRor
bl affichageMess
mov x0,#5
ror x0,x0,#1
bl affichage2
ldr x0,qAdrszMessResultClear
bl affichageMess
mov x0,0b1111
bic x0,x0,#0b100 // clear 3ieme bit
bl affichage2
mov x0,0b11111
bic x0,x0,#6 // clear 2ieme et 3ième bit ( 6 = 110 binary)
bl affichage2
100:
mov x0, #0
mov x8,EXIT
svc 0
qAdrszMessResultAnd: .quad szMessResultAnd
qAdrszMessResultOr: .quad szMessResultOr
qAdrszMessResultEor: .quad szMessResultEor
qAdrszMessResultNot: .quad szMessResultNot
qAdrszMessResultLsl: .quad szMessResultLsl
qAdrszMessResultLsr: .quad szMessResultLsr
qAdrszMessResultAsr: .quad szMessResultAsr
qAdrszMessResultRor: .quad szMessResultRor
qAdrszMessResultClear: .quad szMessResultClear
/******************************************************************/
/* display register in binary */
/******************************************************************/
/* x0 contains the register */
/* x1 contains the address of receipt area */
affichage2:
stp x1,lr,[sp,-16]! // save registers
ldr x1,qAdrsZoneBin
bl conversion2
ldr x0,qAdrsZoneMessBin
bl affichageMess
ldp x1,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
qAdrsZoneBin: .quad sZoneBin
qAdrsZoneMessBin: .quad sMessAffBin
/******************************************************************/
/* register conversion in binary */
/******************************************************************/
/* x0 contains the value */
/* x1 contains the address of receipt area */
conversion2:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x3,64 // position counter of the written character
2: // loop
tst x0,1 // test first bit
lsr x0,x0,#1 // shift right one bit
bne 3f
mov x2,#48 // bit = 0 => character '0'
b 4f
3:
mov x2,#49 // bit = 1 => character '1'
4:
strb w2,[x1,x3] // character in reception area at position counter
subs x3,x3,#1 // 0 bits ?
bgt 2b // no! loop
100:
ldp x3,x4,[sp],16 // restaur 2 registres
ldp x2,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"

View file

@ -0,0 +1,265 @@
report z_bitwise_operations.
class hex_converter definition.
public section.
class-methods:
to_binary
importing
hex_value type x
returning
value(binary_value) type string,
to_decimal
importing
hex_value type x
returning
value(decimal_value) type int4.
endclass.
class hex_converter implementation.
method to_binary.
data(number_of_bits) = xstrlen( hex_value ) * 8.
do number_of_bits times.
get bit sy-index of hex_value into data(bit).
binary_value = |{ binary_value }{ bit }|.
enddo.
endmethod.
method to_decimal.
decimal_value = hex_value.
endmethod.
endclass.
class missing_bitwise_operations definition.
public section.
class-methods:
arithmetic_shift_left
importing
old_value type x
change_with type x
exporting
new_value type x,
arithmetic_shift_right
importing
old_value type x
change_with type x
exporting
new_value type x,
logical_shift_left
importing
old_value type x
change_with type x
exporting
new_value type x,
logical_shift_right
importing
old_value type x
change_with type x
exporting
new_value type x,
rotate_left
importing
old_value type x
change_with type x
exporting
new_value type x,
rotate_right
importing
old_value type x
change_with type x
exporting
new_value type x.
endclass.
class missing_bitwise_operations implementation.
method arithmetic_shift_left.
clear new_value.
new_value = old_value * 2 ** change_with.
endmethod.
method arithmetic_shift_right.
clear new_value.
new_value = old_value div 2 ** change_with.
endmethod.
method logical_shift_left.
clear new_value.
data(bits) = hex_converter=>to_binary( old_value ).
data(length_of_bit_sequence) = strlen( bits ).
bits = shift_left(
val = bits
places = change_with ).
while strlen( bits ) < length_of_bit_sequence.
bits = |{ bits }0|.
endwhile.
do strlen( bits ) times.
data(index) = sy-index - 1.
data(current_bit) = bits+index(1).
if current_bit eq `1`.
set bit sy-index of new_value.
endif.
enddo.
endmethod.
method logical_shift_right.
clear new_value.
data(bits) = hex_converter=>to_binary( old_value ).
data(length_of_bit_sequence) = strlen( bits ).
bits = shift_right(
val = bits
places = change_with ).
while strlen( bits ) < length_of_bit_sequence.
bits = |0{ bits }|.
endwhile.
do strlen( bits ) times.
data(index) = sy-index - 1.
data(current_bit) = bits+index(1).
if current_bit eq `1`.
set bit sy-index of new_value.
endif.
enddo.
endmethod.
method rotate_left.
clear new_value.
data(bits) = hex_converter=>to_binary( old_value ).
bits = shift_left(
val = bits
circular = change_with ).
do strlen( bits ) times.
data(index) = sy-index - 1.
data(current_bit) = bits+index(1).
if current_bit eq `1`.
set bit sy-index of new_value.
endif.
enddo.
endmethod.
method rotate_right.
clear new_value.
data(bits) = hex_converter=>to_binary( old_value ).
bits = shift_right(
val = bits
circular = change_with ).
do strlen( bits ) times.
data(index) = sy-index - 1.
data(current_bit) = bits+index(1).
if current_bit eq `1`.
set bit sy-index of new_value.
endif.
enddo.
endmethod.
endclass.
start-of-selection.
data:
a type x length 4 value 255,
b type x length 4 value 2,
result type x length 4.
write: |a -> { a }, { hex_converter=>to_binary( a ) }, { hex_converter=>to_decimal( a ) }|, /.
write: |b -> { b }, { hex_converter=>to_binary( b ) }, { hex_converter=>to_decimal( b ) }|, /.
result = a bit-and b.
write: |a & b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
result = a bit-or b.
write: |a \| b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
result = a bit-xor b.
write: |a ^ b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
result = bit-not a.
write: |~a -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
missing_bitwise_operations=>arithmetic_shift_left(
exporting
old_value = bit-not a
change_with = b
importing
new_value = result ).
write: |~a << b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
missing_bitwise_operations=>arithmetic_shift_right(
exporting
old_value = bit-not a
change_with = b
importing
new_value = result ).
write: |~a >> b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
missing_bitwise_operations=>logical_shift_left(
exporting
old_value = a
change_with = b
importing
new_value = result ).
write: |a <<< b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
missing_bitwise_operations=>logical_shift_right(
exporting
old_value = bit-not a
change_with = b
importing
new_value = result ).
write: |~a >>> b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
missing_bitwise_operations=>rotate_left(
exporting
old_value = bit-not a
change_with = b
importing
new_value = result ).
write: |~a rotl b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
missing_bitwise_operations=>rotate_right(
exporting
old_value = a
change_with = b
importing
new_value = result ).
write: |a rotr b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.

View file

@ -0,0 +1,7 @@
(defun bitwise (a b)
(list (logand a b)
(logior a b)
(logxor a b)
(lognot a)
(ash a b)
(ash a (- b))))

View file

@ -0,0 +1,64 @@
main:(
PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here #
OP SLC = (BITS b, INT rotate) BITS: b SHL rotate OR b SHR ( bits width - rotate );
OP SRC = (BITS b, INT rotate) BITS: b SHR rotate OR b SHL ( bits width - rotate );
# SRC and SRL are non-standard, but versions are built in to ALGOL 68R's standard prelude #
PRIO XOR = 2;
OP XOR = (BITS p, q) BITS: p AND NOT q OR NOT p AND q;
# XOR is non-standard, but a version is built in to ALGOL 68G's standard prelude #
# ALGOL 68 has 5 different ways of representing a BINary BITS - Bases: 2, 4, 8, 16 and flip/flop #
FORMAT b5 = $"2r"2r32d," 4r"4r16d," 8r"8r11d," 16r"16r8d," "gl$;
OP BBBBB = (BITS b)[]BITS: (b,b,b,b,b);
PROC bitwise = (BITS a, BITS b, INT shift)VOID:
(
printf((
$" bits shorths: "gxgl$, bits shorths, "1 plus the number of extra SHORT BITS types",
$" bits lengths: "gxgl$, bits lengths, "1 plus the number of extra LONG BITS types",
$" max bits: "gl$, max bits,
$" long max bits: "gl$, long max bits,
$" long long max bits: "gl$, long long max bits,
$" bits width: "gxgl$, bits width, "The number of CHAR required to display BITS",
$" long bits width: "gxgl$, long bits width, "The number of CHAR required to display LONG BITS",
$" long long bits width: "gxgl$, long long bits width, "The number of CHAR required to display LONG LONG BITS",
$" bytes shorths: "gxgl$, bytes shorths, "1 plus the number of extra SHORT BYTES types",
$" bytes lengths: "gxgl$, bits lengths, "1 plus the number of extra LONG BYTES types",
$" bytes width: "gxgl$, bytes width, "The number of CHAR required to display BYTES",
$" long bytes width: "gxgl$, long bytes width, "The number of CHAR required to display LONG BYTES"
));
printf(($" a: "f(b5)$, BBBBB a));
printf(($" b: "f(b5)$, BBBBB b));
printf(($" a AND b: "f(b5)$, BBBBB(a AND b)));
printf(($" a OR b: "f(b5)$, BBBBB(a OR b)));
printf(($" a XOR b: "f(b5)$, BBBBB(a XOR b)));
printf(($" NOT b: "f(b5)$, BBBBB NOT a));
printf(($" a SHL "d": "f(b5)$, shift, BBBBB(a SHL shift)));
printf(($" a SHR "d": "f(b5)$, shift, BBBBB(a SHR shift)));
printf(($" a SLC "d": "f(b5)$, shift, BBBBB(a SLC shift)));
printf(($" a SRC "d": "f(b5)$, shift, BBBBB(a SRC shift)))
COMMENT with original ALGOL 68 character set;
printf(($" a AND b: "f(b5)$, BBBBB(a ∧ b)));
printf(($" a OR b: "f(b5)$, BBBBB(a b)));
printf(($" NOT b: "f(b5)$, BBBBB ¬ a));
printf(($" a SHL "d": "f(b5)$, shift, BBBBB(a ↑ shift)));
printf(($" a SHR "d": "f(b5)$, shift, BBBBB(a ↓ shift)));
Also:
printf(($" a AND b: "f(b5)$, BBBBB(a /\ b)));
printf(($" a OR b: "f(b5)$, BBBBB(a \/ b)));
COMMENT
);
bitwise(BIN 255, BIN 170, 5)
# or using alternate representations for 255 and 170 in BITS #
CO
bitwise(2r11111111,2r10101010,5);
bitwise(4r3333,4r2222,5);
bitwise(8r377,8r252,5);
bitwise(16rff,16raa,5)
END CO
)

View file

@ -0,0 +1,13 @@
# unpack (widen) some data back into an a BOOL array #
INT i := 170;
BITS j := BIN i;
[bits width]BOOL k := j;
printf(($g", 8r"8r4d", "8(g)l$, i, j, k[bits width-8+1:]));
# now pack some data back into an INT #
k[bits width-8+1:] := (FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE);
j := bits pack(k);
i := ABS j;
printf(($g", 8r"8r4d", "8(g)l$, i, j, k[bits width-8+1:]))

View file

@ -0,0 +1,19 @@
% performs bitwise and, or, not, left-shift and right shift on the integers n1 and n2 %
% Algol W does not have xor, arithmetic right shift, left rotate or right rotate %
procedure bitOperations ( integer value n1, n2 ) ;
begin
bits b1, b2;
% the Algol W bitwse operations operate on bits values, so we first convert the %
% integers to bits values using the builtin bitstring procedure %
% the results are converted back to integers using the builtin number procedure %
% all Algol W bits and integers are 32 bits quantities %
b1 := bitstring( n1 );
b2 := bitstring( n2 );
% perform the operaations and display the results as integers %
write( n1, " and ", n2, " = ", number( b1 and b2 ) );
write( n1, " or ", n2, " = ", number( b1 or b2 ) );
write( " "
, " not ", n1, " = ", number( not b1 ) );
write( n1, " shl ", n2, " = ", number( b1 shl n2 ), " ( left-shift )" );
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" )
end bitOPerations ;

View file

@ -0,0 +1,158 @@
/* ARM assembly Raspberry PI */
/* program binarydigit.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/* Initialized data */
.data
szMessResultAnd: .asciz "Result of And : \n"
szMessResultOr: .asciz "Result of Or : \n"
szMessResultEor: .asciz "Result of Exclusif Or : \n"
szMessResultNot: .asciz "Result of Not : \n"
szMessResultLsl: .asciz "Result of left shift : \n"
szMessResultLsr: .asciz "Result of right shift : \n"
szMessResultAsr: .asciz "Result of Arithmetic right shift : \n"
szMessResultRor: .asciz "Result of rotate right : \n"
szMessResultRrx: .asciz "Result of rotate right with extend : \n"
szMessResultClear: .asciz "Result of Bit Clear : \n"
sMessAffBin: .ascii "Register value : "
sZoneBin: .space 36,' '
.asciz "\n"
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* save des 2 registres */
ldr r0,iAdrszMessResultAnd
bl affichageMess
mov r0,#5
and r0,#15
bl affichage2
ldr r0,iAdrszMessResultOr
bl affichageMess
mov r0,#5
orr r0,#15
bl affichage2
ldr r0,iAdrszMessResultEor
bl affichageMess
mov r0,#5
eor r0,#15
bl affichage2
ldr r0,iAdrszMessResultNot
bl affichageMess
mov r0,#5
mvn r0,r0
bl affichage2
ldr r0,iAdrszMessResultLsl
bl affichageMess
mov r0,#5
lsl r0,#1
bl affichage2
ldr r0,iAdrszMessResultLsr
bl affichageMess
mov r0,#5
lsr r0,#1
bl affichage2
ldr r0,iAdrszMessResultAsr
bl affichageMess
mov r0,#-5
bl affichage2
mov r0,#-5
asr r0,#1
bl affichage2
ldr r0,iAdrszMessResultRor
bl affichageMess
mov r0,#5
ror r0,#1
bl affichage2
ldr r0,iAdrszMessResultRrx
bl affichageMess
mov r0,#5
mov r1,#15
rrx r0,r1
bl affichage2
ldr r0,iAdrszMessResultClear
bl affichageMess
mov r0,#5
bic r0,#0b100 @ clear 3ieme bit
bl affichage2
bic r0,#4 @ clear 3ieme bit ( 4 = 100 binary)
bl affichage2
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszMessResultAnd: .int szMessResultAnd
iAdrszMessResultOr: .int szMessResultOr
iAdrszMessResultEor: .int szMessResultEor
iAdrszMessResultNot: .int szMessResultNot
iAdrszMessResultLsl: .int szMessResultLsl
iAdrszMessResultLsr: .int szMessResultLsr
iAdrszMessResultAsr: .int szMessResultAsr
iAdrszMessResultRor: .int szMessResultRor
iAdrszMessResultRrx: .int szMessResultRrx
iAdrszMessResultClear: .int szMessResultClear
/******************************************************************/
/* register display in binary */
/******************************************************************/
/* r0 contains the register */
affichage2:
push {r0,lr} /* save registers */
push {r1-r5} /* save others registers */
mrs r5,cpsr /* saves state register in r5 */
ldr r1,iAdrsZoneBin
mov r2,#0 @ read bit position counter
mov r3,#0 @ position counter of the written character
1: @ loop
lsls r0,#1 @ left shift with flags
movcc r4,#48 @ flag carry off character '0'
movcs r4,#49 @ flag carry on character '1'
strb r4,[r1,r3] @ character -> display zone
add r2,r2,#1 @ + 1 read bit position counter
add r3,r3,#1 @ + 1 position counter of the written character
cmp r2,#8 @ 8 bits read
addeq r3,r3,#1 @ + 1 position counter of the written character
cmp r2,#16 @ etc
addeq r3,r3,#1
cmp r2,#24
addeq r3,r3,#1
cmp r2,#31 @ 32 bits shifted ?
ble 1b @ no -> loop
ldr r0,iAdrsZoneMessBin @ address of message result
bl affichageMess @ display result
100:
msr cpsr,r5 /*restaur state register */
pop {r1-r5} /* restaur others registers */
pop {r0,lr}
bx lr
iAdrsZoneBin: .int sZoneBin
iAdrsZoneMessBin: .int sMessAffBin
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registres */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system write */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registres */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */

View file

@ -0,0 +1,10 @@
BEGIN {
n = 11
p = 1
print n " or " p " = " or(n,p)
print n " and " p " = " and(n,p)
print n " xor " p " = " xor(n,p)
print n " << " p " = " lshift(n, p) # left shift
print n " >> " p " = " rshift(n, p) # right shift
printf "not %d = 0x%x\n", n, compl(n) # bitwise complement
}

View file

@ -0,0 +1,24 @@
BYTE FUNC Not(BYTE a)
RETURN (a!$FF)
PROC Main()
BYTE a=[127],b=[2],res
res=a&b
PrintF("%B AND %B = %B%E",a,b,res)
res=a%b
PrintF("%B OR %B = %B%E",a,b,res)
res=a!b
PrintF("%B XOR %B = %B%E",a,b,res)
res=Not(a)
PrintF("NOT %B = %B (by %B XOR $FF)%E",a,res,a)
res=a RSH b
PrintF("%B SHR %B = %B%E",a,b,res)
res=a LSH b
PrintF("%B SHL %B = %B%E",a,b,res)
RETURN

View file

@ -0,0 +1,10 @@
function bitwise(a:int, b:int):void
{
trace("And: ", a & b);
trace("Or: ", a | b);
trace("Xor: ", a ^ b);
trace("Not: ", ~a);
trace("Left Shift: ", a << b);
trace("Right Shift(Arithmetic): ", a >> b);
trace("Right Shift(Logical): ", a >>> b);
}

View file

@ -0,0 +1,23 @@
with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;
procedure Bitwise is
subtype Byte is Unsigned_8;
package Byte_IO is new Ada.Text_Io.Modular_IO (Byte);
A : constant Byte := 2#00011110#;
B : constant Byte := 2#11110100#;
X : constant Byte := 128;
N : constant Natural := 1;
begin
Put ("A and B = "); Byte_IO.Put (Item => A and B, Base => 2); New_Line;
Put ("A or B = "); Byte_IO.Put (Item => A or B, Base => 2); New_Line;
Put ("A xor B = "); Byte_IO.Put (Item => A xor B, Base => 2); New_Line;
Put ("not A = "); Byte_IO.Put (Item => not A, Base => 2); New_Line;
New_Line (2);
Put_Line (Unsigned_8'Image (Shift_Left (X, N)));
Put_Line (Unsigned_8'Image (Shift_Right (X, N)));
Put_Line (Unsigned_8'Image (Shift_Right_Arithmetic (X, N)));
Put_Line (Unsigned_8'Image (Rotate_Left (X, N)));
Put_Line (Unsigned_8'Image (Rotate_Right (X, N)));
end Bitwise;

View file

@ -0,0 +1,9 @@
function bitwise(a, b){
println("a AND b: " + (a & b))
println("a OR b: "+ (a | b))
println("a XOR b: "+ (a ^ b))
println("NOT a: " + ~a)
println("a << b: " + (a << b)) // left shift
println("a >> b: " + (a >> b)) // arithmetic right shift
println("a >>> b: " + (a >>> b)) // logical right shift
}

View file

@ -0,0 +1,355 @@
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
-- BIT OPERATIONS FOR APPLESCRIPT (VIA JAVASCRIPT FOR AUTOMATION)
-- bitAND :: Int -> Int -> Int
on bitAND(x, y)
jsOp2("&", x, y)
end bitAND
-- bitOR :: Int -> Int -> Int
on bitOR(x, y)
jsOp2("|", x, y)
end bitOR
-- bitXOr :: Int -> Int -> Int
on bitXOR(x, y)
jsOp2("^", x, y)
end bitXOR
-- bitNOT :: Int -> Int
on bitNOT(x)
jsOp1("~", x)
end bitNOT
-- (<<) :: Int -> Int -> Int
on |<<|(x, y)
if 31 < y then
0
else
jsOp2("<<", x, y)
end if
end |<<|
-- Logical right shift
-- (>>>) :: Int -> Int -> Int
on |>>>|(x, y)
jsOp2(">>>", x, y)
end |>>>|
-- Arithmetic right shift
-- (>>) :: Int -> Int -> Int
on |>>|(x, y)
jsOp2(">>", x, y)
end |>>|
-- TEST ----------------------------------------------------------
on run
-- Using an ObjC interface to Javascript for Automation
set strClip to bitWise(255, 170)
set the clipboard to strClip
strClip
end run
-- bitWise :: Int -> Int -> String
on bitWise(a, b)
set labels to {"a AND b", "a OR b", "a XOR b", "NOT a", ¬
"a << b", "a >>> b", "a >> b"}
set xs to {bitAND(a, b), bitOR(a, b), bitXOR(a, b), bitNOT(a), ¬
|<<|(a, b), |>>>|(a, b), |>>|(a, b)}
script asBin
property arrow : " -> "
on |λ|(x, y)
justifyRight(8, space, x) & arrow & ¬
justifyRight(14, space, y as text) & arrow & showBinary(y)
end |λ|
end script
unlines({"32 bit signed integers (in two's complement binary encoding)", "", ¬
unlines(zipWith(asBin, ¬
{"a = " & a as text, "b = " & b as text}, {a, b})), "", ¬
unlines(zipWith(asBin, labels, xs))})
end bitWise
-- CONVERSIONS AND DISPLAY
-- bitsFromInt :: Int -> Either String [Bool]
on bitsFromIntLR(x)
script go
on |λ|(n, d, bools)
set xs to {0 d} & bools
if n > 0 then
|λ|(n div 2, n mod 2, xs)
else
xs
end if
end |λ|
end script
set a to abs(x)
if (2.147483647E+9) < a then
|Left|("Integer overflow maximum is (2 ^ 31) - 1")
else
set bs to go's |λ|(a div 2, a mod 2, {})
if 0 > x then
|Right|(replicate(32 - (length of bs), true) & ¬
binSucc(map(my |not|, bs)))
else
set bs to go's |λ|(a div 2, a mod 2, {})
|Right|(replicate(32 - (length of bs), false) & bs)
end if
end if
end bitsFromIntLR
-- Successor function (+1) for unsigned binary integer
-- binSucc :: [Bool] -> [Bool]
on binSucc(bs)
script succ
on |λ|(a, x)
if a then
if x then
Tuple(a, false)
else
Tuple(x, true)
end if
else
Tuple(a, x)
end if
end |λ|
end script
set tpl to mapAccumR(succ, true, bs)
if |1| of tpl then
{true} & |2| of tpl
else
|2| of tpl
end if
end binSucc
-- showBinary :: Int -> String
on showBinary(x)
script showBin
on |λ|(xs)
script bChar
on |λ|(b)
if b then
"1"
else
"0"
end if
end |λ|
end script
map(bChar, xs)
end |λ|
end script
bindLR(my bitsFromIntLR(x), showBin)
end showBinary
-- JXA ------------------------------------------------------------------
--jsOp2 :: String -> a -> b -> c
on jsOp2(strOp, a, b)
bindLR(evalJSLR(unwords({a as text, strOp, b as text})), my |id|) as integer
end jsOp2
--jsOp2 :: String -> a -> b
on jsOp1(strOp, a)
bindLR(evalJSLR(unwords({strOp, a as text})), my |id|) as integer
end jsOp1
-- evalJSLR :: String -> Either String a
on evalJSLR(strJS)
try -- NB if gJSC is global it must be released
-- (e.g. set to null) at end of script
gJSC's evaluateScript
on error
set gJSC to current application's JSContext's new()
log ("new JSC")
end try
set v to unwrap((gJSC's evaluateScript:(strJS))'s toObject())
if v is missing value then
|Left|("JS evaluation error")
else
|Right|(v)
end if
end evalJSLR
-- GENERIC FUNCTIONS --------------------------------------------------
-- Left :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- Absolute value.
-- abs :: Num -> Num
on abs(x)
if 0 > x then
-x
else
x
end if
end abs
-- bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
if missing value is not |Right| of m then
mReturn(mf)'s |λ|(|Right| of m)
else
m
end if
end bindLR
-- foldr :: (a -> b -> b) -> b -> [a] -> b
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
-- id :: a -> a
on |id|(x)
x
end |id|
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- 'The mapAccumR function behaves like a combination of map and foldr;
-- it applies a function to each element of a list, passing an accumulating
-- parameter from |Right| to |Left|, and returning a final value of this
-- accumulator together with the new list.' (see Hoogle)
-- mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumR(f, acc, xs)
script
on |λ|(x, a, i)
tell mReturn(f) to set pair to |λ|(|1| of a, x, i)
Tuple(|1| of pair, (|2| of pair) & |2| of a)
end |λ|
end script
foldr(result, Tuple(acc, []), xs)
end mapAccumR
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- not :: Bool -> Bool
on |not|(p)
not p
end |not|
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- unwords :: [String] -> String
on unwords(xs)
set {dlm, my text item delimiters} to {my text item delimiters, space}
set s to xs as text
set my text item delimiters to dlm
return s
end unwords
-- unwrap :: NSObject -> a
on unwrap(objCValue)
if objCValue is missing value then
missing value
else
set ca to current application
item 1 of ((ca's NSArray's arrayWithObject:objCValue) as list)
end if
end unwrap
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
if 1 > lng then return {}
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith

View file

@ -0,0 +1,488 @@
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
-- BITWISE OPERATIONS FOR APPLESCRIPT ---------------------------------------
-- bitAND :: Int -> Int -> Int
on bitAND(x, y)
bitOp2(my |and|, x, y)
end bitAND
-- bitOR :: Int -> Int -> Int
on bitOR(x, y)
bitOp2(my |or|, x, y)
end bitOR
-- bitXOr :: Int -> Int -> Int
on bitXOR(x, y)
bitOp2(my xor, x, y)
end bitXOR
-- bitNOT :: Int -> Int
on bitNOT(x)
script notBits
on |λ|(xs)
bindLR(intFromBitsLR(map(my |not|, xs)), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(x), notBits)
end bitNOT
-- (<<) :: Int -> Int -> Int
on |<<|(a, b)
script logicLshift
on |λ|(bs)
bindLR(intFromBitsLR(take(32, drop(b, bs) & replicate(b, false))), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), logicLshift)
end |<<|
-- Logical right shift
-- (>>>) :: Int -> Int -> Int
on |>>>|(a, b)
script logicRShift
on |λ|(bs)
bindLR(intFromBitsLR(take(32, replicate(b, false) & drop(b, bs))), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), logicRShift)
end |>>>|
-- Arithmetic right shift
-- (>>) :: Int -> Int -> Int
on |>>|(a, b)
script arithRShift
on |λ|(bs)
if 0 < length of bs then
set sign to item 1 of bs
else
set sign to false
end if
bindLR(intFromBitsLR(take(32, replicate(b, sign) & drop(b, bs))), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), arithRShift)
end |>>|
-- bitRotL :: Int -> Int -> Int
on bitRotL(a, b)
script lRot
on |λ|(bs)
bindLR(intFromBitsLR(rotate(-b, bs)), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), lRot)
end bitRotL
-- bitRotR :: Int -> Int -> Int
on bitRotR(a, b)
script rRot
on |λ|(bs)
bindLR(intFromBitsLR(rotate(b, bs)), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), rRot)
end bitRotR
-- TEST ---------------------------------------------------------------
-- bitWise :: Int -> Int -> String
on bitWise(a, b)
set labels to {"a AND b", "a OR b", "a XOR b", "NOT a", ¬
"a << b", "a >>> b", "a >> b", "ROTL a b", "ROTR a b"}
set xs to {bitAND(a, b), bitOR(a, b), bitXOR(a, b), bitNOT(a), ¬
|<<|(a, b), |>>>|(a, b), |>>|(a, b), bitRotL(a, b), bitRotR(a, b)}
script asBin
property arrow : " -> "
on |λ|(x, y)
justifyRight(8, space, x) & arrow & ¬
justifyRight(14, space, y as text) & arrow & showBinary(y)
end |λ|
end script
unlines({"32 bit signed integers (in two's complement binary encoding)", "", ¬
unlines(zipWith(asBin, ¬
{"a = " & a as text, "b = " & b as text}, {a, b})), "", ¬
unlines(zipWith(asBin, labels, xs))})
end bitWise
on run
-- Assuming 32 bit signed integers (in two's complement binary encoding)
set strClip to bitWise(255, 170)
set the clipboard to strClip
strClip
end run
-- BINARY INTEGER CONVERSIONS AND DISPLAY ------------------------------------------------------------------
-- bitsFromInt :: Int -> Either String [Bool]
on bitsFromIntLR(x)
script go
on |λ|(n, d, bools)
set xs to {0 d} & bools
if n > 0 then
|λ|(n div 2, n mod 2, xs)
else
xs
end if
end |λ|
end script
set a to abs(x)
if (2.147483647E+9) < a then
|Left|("Integer overflow maximum is (2 ^ 31) - 1")
else
set bs to go's |λ|(a div 2, a mod 2, {})
if 0 > x then
|Right|(replicate(32 - (length of bs), true) & ¬
binSucc(map(my |not|, bs)))
else
set bs to go's |λ|(a div 2, a mod 2, {})
|Right|(replicate(32 - (length of bs), false) & bs)
end if
end if
end bitsFromIntLR
-- intFromBitsLR :: [Bool] -> Either String Int
on intFromBitsLR(xs)
script bitSum
on |λ|(x, a, i)
if x then
a + (2 ^ (31 - i))
else
a
end if
end |λ|
end script
set lngBits to length of xs
if 32 < lngBits then
|Left|("Applescript limited to signed 32 bit integers")
else if 1 > lngBits then
|Right|(0 as integer)
else
set bits to (rest of xs)
if item 1 of xs then
|Right|(0 - foldr(bitSum, 1, map(my |not|, bits)) as integer)
else
|Right|(foldr(bitSum, 0, bits) as integer)
end if
end if
end intFromBitsLR
-- showBinary :: Int -> String
on showBinary(x)
script showBin
on |λ|(xs)
script bChar
on |λ|(b)
if b then
"1"
else
"0"
end if
end |λ|
end script
map(bChar, xs)
end |λ|
end script
bindLR(my bitsFromIntLR(x), showBin)
end showBinary
-- bitOp2 :: ((Bool -> Bool -> Bool) -> Int -> Int -> Int
on bitOp2(f, x, y)
script yBits
on |λ|(bitX)
script zipOp
on |λ|(bitY)
bitZipWithLR(f, bitX, bitY)
end |λ|
end script
bindLR(bindLR(bindLR(bitsFromIntLR(y), ¬
zipOp), my intFromBitsLR), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(x), yBits)
end bitOp2
-- bitZipWithLR :: ((a, b) -> c ) -> [Bool] -> [Bool] -> Either String [(Bool, Bool)]
on bitZipWithLR(f, xs, ys)
set intX to length of xs
set intY to length of ys
set intMax to max(intX, intY)
if 33 > intMax then
if intX > intY then
set {bxs, bys} to {xs, ys & replicate(intX - intY, false)}
else
set {bxs, bys} to {xs & replicate(intY - intX, false), ys}
end if
tell mReturn(f)
set lst to {}
repeat with i from 1 to intMax
set end of lst to |λ|(item i of bxs, item i of bys)
end repeat
return |Right|(lst)
end tell
else
|Left|("Above maximum of 32 bits")
end if
end bitZipWithLR
-- Successor function (+1) for unsigned binary integer
-- binSucc :: [Bool] -> [Bool]
on binSucc(bs)
script succ
on |λ|(a, x)
if a then
if x then
Tuple(a, false)
else
Tuple(x, true)
end if
else
Tuple(a, x)
end if
end |λ|
end script
set tpl to mapAccumR(succ, true, bs)
if |1| of tpl then
{true} & |2| of tpl
else
|2| of tpl
end if
end binSucc
-- BOOLEANS ----------------------------------------------------
-- |or| :: Bool -> Bool -> Bool
on |or|(x, y)
x or y
end |or|
-- |and| :: Bool -> Bool -> Bool
on |and|(x, y)
x and y
end |and|
-- xor :: Bool -> Bool -> Bool
on xor(x, y)
(x or y) and not (x and y)
end xor
-- not :: Bool -> Bool
on |not|(p)
not p
end |not|
-- GENERAL ----------------------------------------------------
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
-- Left :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
-- Absolute value.
-- abs :: Num -> Num
on abs(x)
if 0 > x then
-x
else
x
end if
end abs
-- bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
if missing value is not |Right| of m then
mReturn(mf)'s |λ|(|Right| of m)
else
m
end if
end bindLR
-- drop :: Int -> [a] -> [a]
-- drop :: Int -> String -> String
on drop(n, xs)
if class of xs is not string then
if n < length of xs then
items (1 + n) thru -1 of xs
else
{}
end if
else
if n < length of xs then
text (1 + n) thru -1 of xs
else
""
end if
end if
end drop
-- foldr :: (a -> b -> b) -> b -> [a] -> b
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
-- id :: a -> a
on |id|(x)
x
end |id|
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- 'The mapAccumR function behaves like a combination of map and foldr;
-- it applies a function to each element of a list, passing an accumulating
-- parameter from |Right| to |Left|, and returning a final value of this
-- accumulator together with the new list.' (see Hoogle)
-- mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumR(f, acc, xs)
script
on |λ|(x, a, i)
tell mReturn(f) to set pair to |λ|(|1| of a, x, i)
Tuple(|1| of pair, (|2| of pair) & |2| of a)
end |λ|
end script
foldr(result, Tuple(acc, []), xs)
end mapAccumR
-- max :: Ord a => a -> a -> a
on max(x, y)
if x > y then
x
else
y
end if
end max
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- rotate :: Int -> [a] -> [a]
on rotate(n, xs)
set lng to length of xs
if 0 > n then
set d to (-n) mod lng
else
set d to lng - (n mod lng)
end if
drop(d, xs) & take(d, xs)
end rotate
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
if class of xs is string then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
end if
end take
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
if 1 > lng then return {}
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith

View file

@ -0,0 +1,82 @@
on bitwiseAND(n1, n2, registerSize)
set out to 0
-- Multiplying equivalent bit values by each other gives 1 where they're both 1 and 0 otherwise.
repeat with i from 0 to registerSize - 1
tell (2 ^ i) to set out to out + (n1 div it) * (n2 div it) mod 2 * it
end repeat
return out div 1
end bitwiseAND
on bitwiseOR(n1, n2, registerSize)
set out to 0
-- Adding bit values plus a further 1 gives a carry of 1 if either or both values are 1, but not if they're both 0.
repeat with i from 0 to registerSize - 1
tell (2 ^ i) to set out to out + (n1 div it mod 2 + n2 div it mod 2 + 1) div 2 * it
end repeat
return out div 1
end bitwiseOR
on bitwiseXOR(n1, n2, registerSize)
set out to 0
-- Adding bit values gives 1 if they're different and 0 (with or without a carry) if they're both the same.
repeat with i from 0 to registerSize - 1
tell (2 ^ i) to set out to out + (n1 div it + n2 div it) mod 2 * it
end repeat
return out div 1
end bitwiseXOR
on bitwiseNOT(n, registerSize)
-- Subtract n from an all-1s value (ie. from 1 less than 2 ^ registerSize).
tell (2 ^ registerSize) to return (it - 1 - n mod it) div 1
end bitwiseNOT
on leftShift(n, shift, registerSize)
-- Multiply by 2 ^ shift and lose any bits beyond the left of the register.
return n * (2 ^ shift) mod (2 ^ registerSize) div 1
end leftShift
on rightShift(n, shift, registerSize)
-- Divide by 2 ^ shift and lose any bits beyond the right of the register.
return n mod (2 ^ registerSize) div (2 ^ shift)
end rightShift
on arithmeticRightShift(n, shift, registerSize)
set n to n mod (2 ^ registerSize)
-- If the number's positive and notionally sets the sign bit, reinterpret it as a negative.
tell (2 ^ (registerSize - 1)) to if (n it) then set n to n mod it - it
-- Right shift by the appropriate amount
set out to n div (2 ^ shift)
-- If the result for a negative is 0, change it to -1.
if ((n < 0) and (out is 0)) then set out to -1
return out
end arithmeticRightShift
on leftRotate(n, shift, registerSize)
-- Cut the register at the appropriate point, left shift the right side and right shift the left by the appropriate amounts.
set shift to shift mod (registerSize)
return leftShift(n, shift, registerSize) + rightShift(n, registerSize - shift, registerSize)
end leftRotate
on rightRotate(n, shift, registerSize)
-- As left rotate, but applying the shift amounts to the opposite sides.
set shift to shift mod registerSize
return rightShift(n, shift, registerSize) + leftShift(n, registerSize - shift, registerSize)
end rightRotate
bitwiseAND(92, 7, 16) --> 4
bitwiseOR(92, 7, 16) --> 95
bitwiseXOR(92, 7, 16) --> 91
bitwiseNOT(92, 16) --> 64453
bitwiseNOT(92, 8) --> 163
bitwiseNOT(92, 32) --> 4.294967203E+9
leftShift(92, 7, 16) --> 11776
leftShift(92, 7, 8) --> 0
rightShift(92, 7, 16) --> 0
arithmeticRightShift(92, 7, 16) --> 0
arithmeticRightShift(-92, 7, 16) --> -1
leftRotate(92, 7, 8) --> 46
rightRotate(92, 7, 8) --> 184
rightRotate(92, 7, 16) --> 47104

View file

@ -0,0 +1,9 @@
a: 255
b: 2
print [a "AND" b "=" and a b]
print [a "OR" b "=" or a b]
print [a "XOR" b "=" xor a b]
print ["NOT" a "=" not a]
print [a "SHL" b "=" shl a b]
print [a "SHR" b "=" shr a b]

View file

@ -0,0 +1,10 @@
bitwise(3, 4)
bitwise(a, b)
{
MsgBox % "a and b: " . a & b
MsgBox % "a or b: " . a | b
MsgBox % "a xor b: " . a ^ b
MsgBox % "not a: " . ~a ; treated as unsigned integer
MsgBox % "a << b: " . a << b ; left shift
MsgBox % "a >> b: " . a >> b ; arithmetic right shift
}

View file

@ -0,0 +1,12 @@
bitwise(255, 5)
Func bitwise($a, $b)
MsgBox(1, '', _
$a & " AND " & $b & ": " & BitAND($a, $b) & @CRLF & _
$a & " OR " & $b & ": " & BitOR($a, $b) & @CRLF & _
$a & " XOR " & $b & ": " & BitXOR($a, $b) & @CRLF & _
"NOT " & $a & ": " & BitNOT($a) & @CRLF & _
$a & " SHL " & $b & ": " & BitShift($a, $b * -1) & @CRLF & _
$a & " SHR " & $b & ": " & BitShift($a, $b) & @CRLF & _
$a & " ROL " & $b & ": " & BitRotate($a, $b) & @CRLF & _
$a & " ROR " & $b & ": " & BitRotate($a, $b * -1) & @CRLF )
EndFunc

View file

@ -0,0 +1,9 @@
Lbl BITS
r₁→A
r₂→B
Disp "AND:",A·B▶Dec,i
Disp "OR:",AᕀB▶Dec,i
Disp "XOR:",A▫B▶Dec,i
Disp "NOT:",not(A)ʳ▶Dec,i
.No language support for shifts or rotations
Return

View file

@ -0,0 +1,6 @@
SUB bitwise (a, b)
PRINT a AND b
PRINT a OR b
PRINT a XOR b
PRINT NOT a
END SUB

View file

@ -0,0 +1,12 @@
SUB bitwise (a AS Integer, b AS Integer)
DIM u AS UInteger
PRINT "a AND b = "; a AND b
PRINT "a OR b = "; a OR b
PRINT "a XOR b = "; a XOR b
PRINT "NOT a = "; NOT a
PRINT "a SHL b = "; a SHL b
PRINT "a SHR b (arithmetic) = "; a SHR b
u = a
PRINT "a SHR b (logical) = "; u SHR b
END SUB

View file

@ -0,0 +1,8 @@
# bitwise operators - floating point numbers will be cast to integer
a = 0b00010001
b = 0b11110000
print a
print int(a * 2) # shift left (multiply by 2)
print a \ 2 # shift right (integer divide by 2)
print a | b # bitwise or on two integer values
print a & b # bitwise or on two integer values

View file

@ -0,0 +1,12 @@
number1% = &89ABCDEF
number2% = 8
PRINT ~ number1% AND number2% : REM bitwise AND
PRINT ~ number1% OR number2% : REM bitwise OR
PRINT ~ number1% EOR number2% : REM bitwise exclusive-OR
PRINT ~ NOT number1% : REM bitwise NOT
PRINT ~ number1% << number2% : REM left shift
PRINT ~ number1% >>> number2% : REM right shift (logical)
PRINT ~ number1% >> number2% : REM right shift (arithmetic)
PRINT ~ (number1% << number2%) OR (number1% >>> (32-number2%)) : REM left rotate
PRINT ~ (number1% >>> number2%) OR (number1% << (32-number2%)) : REM right rotate

View file

@ -0,0 +1 @@
({5 9}) ({cand} {cor} {cnor} {cxor} {cxnor} {shl} {shr} {ashr} {rol}) cart ! {give <- cp -> compose !} over ! {eval} over ! {;} each

View file

@ -0,0 +1 @@
9 cnot ;

View file

@ -0,0 +1,73 @@
@echo off
setlocal
set /a "a=%~1, b=%~2"
call :num2bin %a% aStr
call :num2bin %b% bStr
::AND
set /a "val=a&b"
call :display "%a% AND %b%" %val% %aStr% %bStr%
::OR
set /a "val=a|b"
call :display "%a% OR %b%" %val% %aStr% %bStr%
::XOR
set /a "val=a^b"
call :display "%a% XOR %b%" %val% %aStr% %bStr%
::NOT
set /a "val=~a"
call :display "NOT %a%" %val% %aStr%
::LEFT SHIFT
set /a "val=a<<b"
call :display "%a% Left Shift %b%" %val% %aStr%
::ARITHMETIC RIGHT SHIFT
set /a "val=a>>b"
call :display "%a% Arithmetic Right Shift %b%" %val% %aStr%
::The remaining operations do not have native support
::The implementations use additional operators
:: %% = mod
:: ! = logical negation where !(zero)=1 and !(non-zero)=0
:: * = multiplication
:: - = subtraction
::LOGICAL RIGHT SHIFT (No native support)
set /a "val=(a>>b)&~((0x80000000>>b-1)*!!b)"
call :display "%a% Logical Right Shift %b%" %val% %aStr%
::ROTATE LEFT (No native support)
set /a "val=(a<<b%%32) | (a>>32-b%%32)&~((0x80000000>>31-b%%32)*!!(32-b%%32))"
call :display "%a% Rotate Left %b%" %val% %aStr%
::ROTATE RIGHT (No native support)
set /a "val=(a<<32-b%%32) | (a>>b%%32)&~((0x80000000>>b%%32-1)*!!(b%%32)) "
call :display "%a% Rotate Right %b%" %val% %aStr%
exit /b
:display op result aStr [bStr]
echo(
echo %~1 = %2
echo %3
if "%4" neq "" echo %4
call :num2bin %2
exit /b
:num2bin IntVal [RtnVar]
setlocal enableDelayedExpansion
set n=%~1
set rtn=
for /l %%b in (0,1,31) do (
set /a "d=n&1, n>>=1"
set rtn=!d!!rtn!
)
(endlocal & rem -- return values
if "%~2" neq "" (set %~2=%rtn%) else echo %rtn%
)
exit /b

View file

@ -0,0 +1,25 @@
#eX~T~T_#
###>N{` AND `~{~` = `&{Nz1~3J
UXe#
##>{` OR `~{~` = `|{Nz1~5J
UXe#
##>{` XOR `~{~` = `${Nz1~7J
UXe#
##>`NOT `{` = `!{Nz1~9J
UXe#
##>{` << `~{~` = `({Nz1~9PPJ
UXe#
##>{` >>> `~{~` = `){` (logical shift right)`N7F+M~1~J
UXe#
##>{` ROL `~{~` = `[{N7F+P~1~J
UXe#
##>{` ROR `~{~` = `]{NN8F+P~1~J
UXe#
##>`Arithmetic shift right is not originally implemented in beeswax.`N q
qN`,noitagen yb dezilaer eb nac srebmun evitagen rof RSA ,yllacinhcet tuB`N<
##>`logical shift right, and negating the result again:`NN7F++~1~J
UXe# #>e#
#>~1~[&'pUX{` >> `~{~` = `){` , interpreted as (positive) signed Int64 number (MSB=0), equivalent to >>>`NN;
###
>UX`-`!P{M!` >> `~{~` = `!)!`-`M!{` , interpreted as (negative) signed Int64 number (MSB=1)`NN;
#>e#

View file

@ -0,0 +1,19 @@
julia> beeswax("Bitops.bswx",0,0.0,Int(20000))
i9223653511831486512
i48
9223653511831486512 AND 48 = 48
9223653511831486512 OR 48 = 9223653511831486512
9223653511831486512 XOR 48 = 9223653511831486464
NOT 9223653511831486512 = 9223090561878065103
9223653511831486512 << 48 = 13510798882111488
9223653511831486512 >>> 48 = 32769 (logical shift right)
9223653511831486512 ROL 48 = 13651540665434112
9223653511831486512 ROR 48 = 3178497
Arithmetic shift right is not originally implemented in beeswax.
But technically, ASR for negative numbers can be realized by negation,
logical shift right, and negating the result again:
-9223090561878065104 >> 48 = -32767 , interpreted as (negative) signed Int64 number (MSB=1)

View file

@ -0,0 +1 @@
A>>B = NOT(NOT(A)>>>B)

View file

@ -0,0 +1,2 @@
A ROL B = A<<(B%64)+A>>>(64-B%64)
A ROR B = A>>>(B%64)+A<<(64-B%64)

View file

@ -0,0 +1,21 @@
> v MCR >v
1 2 3 4 5 6>61g-:| 8 9
>&&\481p >88*61p371p >:61g\`!:68*+71g81gp| 7 >61g2/61p71g1+71pv
>v>v>v>v < > ^
>#A 1 $^ ^ <
B 6^ <
^>^>^>^1 C |!`5p18:+1g18$ <
^ 9 p#p17*93p189p150 < >61g71g81gg+71g81gpv D
>071g81gp v ^ <
AND >+2\`!#^_> v
XOR +2% #^_> v
OR +1\`!#^_> v
NOT ! #^_> v
LSHFT 0 #^_>48*71g3+81gp v
RSHFT $ 48*71g3+81gp #^_>v E
END v #^_> >61g2*61pv
@ F
v_^# `2:<
>71g81gg.48*71g2+81gp79*1-71g2+81g1+pv
^ <_v#!`2p15:+1g15p18+1g18<
^ < G

View file

@ -0,0 +1,23 @@
#include <iostream>
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n'; // Note: parentheses are needed because & has lower precedence than <<
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
// Note: the C/C++ shift operators are not guaranteed to work if the shift count (that is, b)
// is negative, or is greater or equal to the number of bits in the integer being shifted.
std::cout << "a shl b: " << (a << b) << '\n'; // Note: "<<" is used both for output and for left shift
std::cout << "a shr b: " << (a >> b) << '\n'; // typically arithmetic right shift, but not guaranteed
unsigned int ua = a;
std::cout << "a lsr b: " << (ua >> b) << '\n'; // logical right shift (guaranteed)
// there are no rotation operators in C++, but as of c++20 there is a standard-library rotate function.
// The rotate function works for all rotation amounts, but the integer being rotated must always be an
// unsigned integer.
std::cout << "a rol b: " << std::rotl(ua, b) << '\n';
std::cout << "a ror b: " << std::rotr(ua, b) << '\n';
}

View file

@ -0,0 +1,14 @@
static void bitwise(int a, int b)
{
Console.WriteLine("a and b is {0}", a & b);
Console.WriteLine("a or b is {0}", a | b);
Console.WriteLine("a xor b is {0}", a ^ b);
Console.WriteLine("not a is {0}", ~a);
Console.WriteLine("a lshift b is {0}", a << b);
Console.WriteLine("a arshift b is {0}", a >> b); // When the left operand of the >> operator is of a signed integral type,
// the operator performs an arithmetic shift right
uint c = (uint)a;
Console.WriteLine("c rshift b is {0}", c >> b); // When the left operand of the >> operator is of an unsigned integral type,
// the operator performs a logical shift right
// there are no rotation operators in C#
}

View file

@ -0,0 +1,14 @@
void bitwise(int a, int b)
{
printf("a and b: %d\n", a & b);
printf("a or b: %d\n", a | b);
printf("a xor b: %d\n", a ^ b);
printf("not a: %d\n", ~a);
printf("a << n: %d\n", a << b); /* left shift */
printf("a >> n: %d\n", a >> b); /* on most platforms: arithmetic right shift */
/* convert the signed integer into unsigned, so it will perform logical shift */
unsigned int c = a;
printf("c >> b: %d\n", c >> b); /* logical right shift */
/* there are no rotation operators in C */
return 0;
}

View file

@ -0,0 +1,5 @@
/* rotate x to the right by s bits */
unsigned int rotr(unsigned int x, unsigned int s)
{
return (x >> s) | (x << 32 - s);
}

View file

@ -0,0 +1,5 @@
rotr:
movl 4(%esp), %eax ; arg1: x
movl 8(%esp), %ecx ; arg2: s
rorl %cl, %eax ; right rotate x by s
ret

View file

@ -0,0 +1,35 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. bitwise-ops.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 a PIC 1(32) USAGE BIT.
01 b PIC 1(32) USAGE BIT.
01 result PIC 1(32) USAGE BIT.
01 result-disp REDEFINES result PIC S9(9) COMP.
LINKAGE SECTION.
01 a-int USAGE BINARY-LONG.
01 b-int USAGE BINARY-LONG.
PROCEDURE DIVISION USING a-int, b-int.
MOVE FUNCTION BOOLEAN-OF-INTEGER(a-int, 32) TO a
MOVE FUNCTION BOOLEAN-OF-INTEGER(b-int, 32) TO b
COMPUTE result = a B-AND b
DISPLAY "a and b is " result-disp
COMPUTE result = a B-OR b
DISPLAY "a or b is " result-disp
COMPUTE result = B-NOT a
DISPLAY "Not a is " result-disp
COMPUTE result = a B-XOR b
DISPLAY "a exclusive-or b is " result-disp
*> COBOL does not have shift or rotation operators.
GOBACK
.

View file

@ -0,0 +1,41 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. mf-bitwise-ops.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 result USAGE BINARY-LONG.
78 arg-len VALUE LENGTH OF result.
LINKAGE SECTION.
01 a USAGE BINARY-LONG.
01 b USAGE BINARY-LONG.
PROCEDURE DIVISION USING a, b.
main-line.
MOVE b TO result
CALL "CBL_AND" USING a, result, VALUE arg-len
DISPLAY "a and b is " result
MOVE b TO result
CALL "CBL_OR" USING a, result, VALUE arg-len
DISPLAY "a or b is " result
MOVE a TO result
CALL "CBL_NOT" USING result, VALUE arg-len
DISPLAY "Not a is " result
MOVE b TO result
CALL "CBL_XOR" USING a, result, VALUE arg-len
DISPLAY "a exclusive-or b is " result
MOVE b TO result
CALL "CBL_EQ" USING a, result, VALUE arg-len
DISPLAY "Logical equivalence of a and b is " result
MOVE b TO result
CALL "CBL_IMP" USING a, result, VALUE arg-len
DISPLAY "Logical implication of a and b is " result
GOBACK
.

View file

@ -0,0 +1,7 @@
(bit-and x y)
(bit-or x y)
(bit-xor x y)
(bit-not x)
(bit-shift-left x n)
(bit-shift-right x n)
;;There is no built-in for rotation.

View file

@ -0,0 +1,12 @@
f = (a, b) ->
p "and", a & b
p "or", a | b
p "xor", a ^ b
p "not", ~a
p "<<", a << b
p ">>", a >> b
# no rotation shifts that I know of
p = (label, n) -> console.log label, n
f(10,2)

View file

@ -0,0 +1,7 @@
> coffee foo.coffee
and 2
or 10
xor 8
not -11
<< 40
>> 2

View file

@ -0,0 +1,6 @@
10 INPUT "A="; A
20 INPUT "B="; B
30 PRINT "A AND B =" A AND B :rem AND
40 PRINT "A OR B =" A OR B :rem OR
50 PRINT "A XOR B =" (A AND(NOT B))OR((NOT A)AND B) :rem XOR
60 PRINT "NOT A =" NOT A :rem NOT

View file

@ -0,0 +1,9 @@
(defun bitwise (a b)
(print (logand a b)) ; AND
(print (logior a b)) ; OR ("ior" = inclusive or)
(print (logxor a b)) ; XOR
(print (lognot a)) ; NOT
(print (ash a b)) ; arithmetic left shift (positive 2nd arg)
(print (ash a (- b))) ; arithmetic right shift (negative 2nd arg)
; no logical shift
)

View file

@ -0,0 +1,9 @@
(defun shl (x width bits)
"Compute bitwise left shift of x by 'bits' bits, represented on 'width' bits"
(logand (ash x bits)
(1- (ash 1 width))))
(defun shr (x width bits)
"Compute bitwise right shift of x by 'bits' bits, represented on 'width' bits"
(logand (ash x (- bits))
(1- (ash 1 width))))

View file

@ -0,0 +1,13 @@
(defun rotl (x width bits)
"Compute bitwise left rotation of x by 'bits' bits, represented on 'width' bits"
(logior (logand (ash x (mod bits width))
(1- (ash 1 width)))
(logand (ash x (- (- width (mod bits width))))
(1- (ash 1 width)))))
(defun rotr (x width bits)
"Compute bitwise right rotation of x by 'bits' bits, represented on 'width' bits"
(logior (logand (ash x (- (mod bits width)))
(1- (ash 1 width)))
(logand (ash x (- width (mod bits width)))
(1- (ash 1 width)))))

View file

@ -0,0 +1,23 @@
T rot(T)(in T x, in int shift) pure nothrow @nogc {
return (x >>> shift) | (x << (T.sizeof * 8 - shift));
}
void testBit(in int a, in int b) {
import std.stdio;
writefln("Input: a = %d, b = %d", a, b);
writefln("AND : %8b & %08b = %032b (%4d)", a, b, a & b, a & b);
writefln(" OR : %8b | %08b = %032b (%4d)", a, b, a | b, a | b);
writefln("XOR : %8b ^ %08b = %032b (%4d)", a, b, a ^ b, a ^ b);
writefln("LSH : %8b << %08b = %032b (%4d)", a, b, a << b, a << b);
writefln("RSH : %8b >> %08b = %032b (%4d)", a, b, a >> b, a >> b);
writefln("NOT : %8s ~ %08b = %032b (%4d)", "", a, ~a, ~a);
writefln("ROT : rot(%8b, %d) = %032b (%4d)",
a, b, rot(a, b), rot(a, b));
}
void main() {
immutable int a = 0b_1111_1111; // bit literal 255
immutable int b = 0b_0000_0010; // bit literal 2
testBit(a, b);
}

View file

@ -0,0 +1,6 @@
PrintLn('2 and 3 = '+IntToStr(2 and 3));
PrintLn('2 or 3 = '+IntToStr(2 or 3));
PrintLn('2 xor 3 = '+IntToStr(2 xor 3));
PrintLn('not 2 = '+IntToStr(not 2));
PrintLn('2 shl 3 = '+IntToStr(2 shl 3));
PrintLn('2 shr 3 = '+IntToStr(2 shr 3));

View file

@ -0,0 +1,14 @@
program Bitwise;
{$APPTYPE CONSOLE}
begin
Writeln('2 and 3 = ', 2 and 3);
Writeln('2 or 3 = ', 2 or 3);
Writeln('2 xor 3 = ', 2 xor 3);
Writeln('not 2 = ', not 2);
Writeln('2 shl 3 = ', 2 shl 3);
Writeln('2 shr 3 = ', 2 shr 3);
// there are no built-in rotation operators in Delphi
Readln;
end.

View file

@ -0,0 +1,10 @@
def bitwise(a :int, b :int) {
println(`Bitwise operations:
a AND b: ${a & b}
a OR b: ${a | b}
a XOR b: ${a ^ b}
NOT a: " + ${~a}
a left shift b: ${a << b}
a right shift b: ${a >> b}
`)
}

View file

@ -0,0 +1,29 @@
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION
BitAND := A & B;
BitOR := A | B;
BitXOR := A ^ B;
BitNOT := BNOT A;
BitSL := A << B;
BitSR := A >> B;
DS := DATASET([{A,B,'Bitwise AND:',BitAND},
{A,B,'Bitwise OR:',BitOR},
{A,B,'Bitwise XOR',BitXOR},
{A,B,'Bitwise NOT A:',BitNOT},
{A,B,'ShiftLeft A:',BitSL},
{A,B,'ShiftRight A:',BitSR}],
{INTEGER AVal,INTEGER BVal,STRING15 valuetype,INTEGER val});
RETURN DS;
END;
BitwiseOperations(255,5);
//right arithmetic shift, left and right rotate not implemented
/*
OUTPUT:
255 5 Bitwise AND: 5
255 5 Bitwise OR: 255
255 5 Bitwise XOR 250
255 5 Bitwise NOT A: -256
255 5 ShiftLeft A: 8160
255 5 ShiftRight A: 7
*/

View file

@ -0,0 +1,9 @@
# numbers are doubles, bit operations use 32 bits and are unsigned
x = 11
y = 2
print bitnot x
print bitand x y
print bitor x y
print bitxor x y
print bitshift x y
print bitshift x -y

View file

@ -0,0 +1,31 @@
module BitwiseOps {
@Inject Console console;
void run() {
for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF]) { // <- test data
static String hex(Int64 n) { // <- this is a locally scoped helper function
// formats the integer as a hex string, but drops the leading '0' bytes
return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
}
console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
| {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
| {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
| {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
| NOT {hex(n1)} = {hex(~n1)}
| left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
| right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
| right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
| left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
| right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
| leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
| rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
| leading zero count of {hex(n1)} = {n1.leadingZeroCount}
| trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
| bit count (aka "population") of {hex(n1)} = {n1.bitCount}
| reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
| reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
|
);
}
}
}

View file

@ -0,0 +1,19 @@
import extensions;
extension testOp
{
bitwiseTest(y)
{
console.printLine(self," and ",y," = ",self.and(y));
console.printLine(self," or ",y," = ",self.or(y));
console.printLine(self," xor ",y," = ",self.xor(y));
console.printLine("not ",self," = ",self.Inverted);
console.printLine(self," shr ",y," = ",self.shiftRight(y));
console.printLine(self," shl ",y," = ",self.shiftLeft(y));
}
}
public program()
{
console.loadLineTo(new Integer()).bitwiseTest(console.loadLineTo(new Integer()))
}

View file

@ -0,0 +1,22 @@
defmodule Bitwise_operation do
use Bitwise
def test(a \\ 255, b \\ 170, c \\ 2) do
IO.puts "Bitwise function:"
IO.puts "band(#{a}, #{b}) = #{band(a, b)}"
IO.puts "bor(#{a}, #{b}) = #{bor(a, b)}"
IO.puts "bxor(#{a}, #{b}) = #{bxor(a, b)}"
IO.puts "bnot(#{a}) = #{bnot(a)}"
IO.puts "bsl(#{a}, #{c}) = #{bsl(a, c)}"
IO.puts "bsr(#{a}, #{c}) = #{bsr(a, c)}"
IO.puts "\nBitwise as operator:"
IO.puts "#{a} &&& #{b} = #{a &&& b}"
IO.puts "#{a} ||| #{b} = #{a ||| b}"
IO.puts "#{a} ^^^ #{b} = #{a ^^^ b}"
IO.puts "~~~#{a} = #{~~~a}"
IO.puts "#{a} <<< #{c} = #{a <<< c}"
IO.puts "#{a} >>> #{c} = #{a >>> c}"
end
end
Bitwise_operation.test

View file

@ -0,0 +1,13 @@
-module(bitwise_operations).
-export([test/0]).
test() ->
A = 255,
B = 170,
io:format("~p band ~p = ~p\n",[A,B,A band B]),
io:format("~p bor ~p = ~p\n",[A,B,A bor B]),
io:format("~p bxor ~p = ~p\n",[A,B,A bxor B]),
io:format("not ~p = ~p\n",[A,bnot A]),
io:format("~p bsl ~p = ~p\n",[A,B,A bsl B]),
io:format("~p bsr ~p = ~p\n",[A,B,A bsr B]).

View file

@ -0,0 +1,6 @@
255 band 170 = 170
255 bor 170 = 255
255 bxor 170 = 85
not 255 = -256
255 bsl 170 = 381627307539845370001346183518875822092557105621893120
255 bsr 170 = 0

View file

@ -0,0 +1,9 @@
let bitwise a b =
printfn "a and b: %d" (a &&& b)
printfn "a or b: %d" (a ||| b)
printfn "a xor b: %d" (a ^^^ b)
printfn "not a: %d" (~~~a)
printfn "a shl b: %d" (a <<< b)
printfn "a shr b: %d" (a >>> b) // arithmetic shift
printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift
// No rotation operators.

View file

@ -0,0 +1,6 @@
10 3
\$@$@$@$@\ { 3 copies }
"a & b = "&."
a | b = "|."
~a = "%~."
"

View file

@ -0,0 +1,9 @@
"a=" "b=" [ write readln string>number ] bi@
{
[ bitand "a AND b: " write . ]
[ bitor "a OR b: " write . ]
[ bitxor "a XOR b: " write . ]
[ drop bitnot "NOT a: " write . ]
[ abs shift "a asl b: " write . ]
[ neg shift "a asr b: " write . ]
} 2cleave

View file

@ -0,0 +1,8 @@
a=255
b=5
a AND b: 5
a OR b: 255
a XOR b: 250
NOT a: -256
a asl b: 8160
a asr b: 7

View file

@ -0,0 +1,11 @@
: arshift 0 ?do 2/ loop ; \ 2/ is an arithmetic shift right by one bit (2* shifts left one bit)
: bitwise ( a b -- )
cr ." a = " over . ." b = " dup .
cr ." a and b = " 2dup and .
cr ." a or b = " 2dup or .
cr ." a xor b = " 2dup xor .
cr ." not a = " over invert .
cr ." a shl b = " 2dup lshift .
cr ." a shr b = " 2dup rshift .
cr ." a ashr b = " 2dup arshift .
2drop ;

View file

@ -0,0 +1,27 @@
integer :: i, j = -1, k = 42
logical :: a
i = bit_size(j) ! returns the number of bits in the given INTEGER variable
! bitwise boolean operations on integers
i = iand(k, j) ! returns bitwise AND of K and J
i = ior(k, j) ! returns bitwise OR of K and J
i = ieor(k, j) ! returns bitwise EXCLUSIVE OR of K and J
i = not(j) ! returns bitwise NOT of J
! single-bit integer/logical operations (bit positions are zero-based)
a = btest(i, 4) ! returns logical .TRUE. if bit position 4 of I is 1, .FALSE. if 0
i = ibclr(k, 8) ! returns value of K with 8th bit position "cleared" (set to 0)
i = ibset(k, 13) ! returns value of K with 13th bit position "set" (set to 1)
! multi-bit integer operations
i = ishft(k, j) ! returns value of K shifted by J bit positions, with ZERO fill
! (right shift if J < 0 and left shift if J > 0).
i = ishftc(k, j) ! returns value of K shifted CIRCULARLY by J bit positions
! (right circular shift if J < 0 and left if J > 0)
i = ishftc(k, j, 20) ! returns value as before except that ONLY the 20 lowest order
! (rightmost) bits are circularly shifted
i = ibits(k, 7, 8) ! extracts 8 contiguous bits from K starting at position 7 and
! returns them as the rightmost bits of an otherwise
! zero-filled integer. For non-negative K this is
! arithmetically equivalent to: MOD((K / 2**7), 2**8)

View file

@ -0,0 +1 @@
call mvbits(k, 2, 4, j, 0) ! copy a sequence of 4 bits from k starting at bit 2 into j starting at bit 0

View file

@ -0,0 +1,25 @@
program bits_rosetta
implicit none
call bitwise(14,3)
contains
subroutine bitwise(a,b)
implicit none
integer, intent(in):: a,b
character(len=*), parameter :: fmt1 = '(2(a,i10))'
character(len=*),parameter :: fmt2 = '(3(a,b32.32),i20)'
write(*,fmt1) 'input a=',a,' b=',b
write(*,fmt2) 'and : ', a,' & ',b,' = ',iand(a, b),iand(a, b)
write(*,fmt2) 'or : ', a,' | ',b,' = ',ior(a, b),ior(a, b)
write(*,fmt2) 'xor : ', a,' ^ ',b,' = ',ieor(a, b),ieor(a, b)
write(*,fmt2) 'lsh : ', a,' << ',b,' = ',shiftl(a,b),shiftl(a,b) !since F2008, otherwise use ishft(a, abs(b))
write(*,fmt2) 'rsh : ', a,' >> ',b,' = ',shiftr(a,b),shiftr(a,b) !since F2008, otherwise use ishft(a, -abs(b))
write(*,fmt2) 'not : ', a,' ~ ',b,' = ',not(a),not(a)
write(*,fmt2) 'rot : ', a,' r ',b,' = ',ishftc(a,-abs(b)),ishftc(a,-abs(b))
end subroutine bitwise
end program bits_rosetta

View file

@ -0,0 +1,8 @@
Input a= 14 b= 3
AND : 00000000000000000000000000001110 & 00000000000000000000000000000011 = 00000000000000000000000000000010 2
OR : 00000000000000000000000000001110 | 00000000000000000000000000000011 = 00000000000000000000000000001111 15
XOR : 00000000000000000000000000001110 ^ 00000000000000000000000000000011 = 00000000000000000000000000001101 13
LSH : 00000000000000000000000000001110 << 00000000000000000000000000000011 = 00000000000000000000000001110000 112
RSH : 00000000000000000000000000001110 >> 00000000000000000000000000000011 = 00000000000000000000000000000001 1
NOT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11111111111111111111111111110001 -15
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823

Some files were not shown because too many files have changed in this diff Show more