This commit is contained in:
Ingy döt Net 2013-04-10 16:19:29 -07:00
parent e5e8880e41
commit 518da4a923
1019 changed files with 15877 additions and 0 deletions

View file

@ -0,0 +1 @@
{{basic data operation}}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.

View file

@ -0,0 +1,2 @@
---
note: Discrete math

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,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,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,24 @@
with Ada.Text_Io; use Ada.Text_Io;
with Interfaces; use Interfaces;
procedure Bitwise is
subtype Byte is Unsigned_8;
package Byte_Io is new Ada.Text_Io.Modular_Io(Byte);
A : Byte := 255;
B : Byte := 170;
X : Byte := 128;
N : Natural := 1;
begin
Put_Line("A and B = "); Byte_Io.Put(Item => A and B, Base => 2);
Put_Line("A or B = "); Byte_IO.Put(Item => A or B, Base => 2);
Put_Line("A xor B = "); Byte_Io.Put(Item => A xor B, Base => 2);
Put_Line("Not A = "); Byte_IO.Put(Item => not A, Base => 2);
New_Line(2);
Put_Line(Unsigned_8'Image(Shift_Left(X, N))); -- Left shift
Put_Line(Unsigned_8'Image(Shift_Right(X, N))); -- Right shift
Put_Line(Unsigned_8'Image(Shift_Right_Arithmetic(X, N))); -- Right Shift Arithmetic
Put_Line(Unsigned_8'Image(Rotate_Left(X, N))); -- Left rotate
Put_Line(Unsigned_8'Image(Rotate_Right(X, N))); -- Right rotate
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,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,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) # right shift (multiply by 2)
print a \ 2 # left shift (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,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,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,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,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,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,45 @@
package main
import "fmt"
func bitwise(a, b int16) (and, or, xor, not, shl, shr, ras, rol, ror int16) {
// the first four are easy
and = a & b
or = a | b
xor = a ^ b
not = ^a
// for all shifts, the right operand (shift distance) must be unsigned.
// use abs(b) for a non-negative value.
if b < 0 {
b = -b
}
ub := uint(b)
shl = a << ub
// for right shifts, if the left operand is unsigned, Go performs
// a logical shift; if signed, an arithmetic shift.
shr = int16(uint16(a) >> ub)
ras = a >> ub
// rotates
rol = a << ub | int16(uint16(a) >> (16-ub))
ror = int16(uint16(a) >> ub) | a << (16-ub)
return
}
func main() {
var a, b int16 = -460, 6
and, or, xor, not, shl, shr, ras, rol, ror := bitwise(a, b)
fmt.Printf("a: %016b\n", uint16(a))
fmt.Printf("b: %016b\n", uint16(b))
fmt.Printf("and: %016b\n", uint16(and))
fmt.Printf("or: %016b\n", uint16(or))
fmt.Printf("xor: %016b\n", uint16(xor))
fmt.Printf("not: %016b\n", uint16(not))
fmt.Printf("shl: %016b\n", uint16(shl))
fmt.Printf("shr: %016b\n", uint16(shr))
fmt.Printf("ras: %016b\n", uint16(ras))
fmt.Printf("rol: %016b\n", uint16(rol))
fmt.Printf("ror: %016b\n", uint16(ror))
}

View file

@ -0,0 +1,18 @@
import Data.Bits
bitwise :: Int -> Int -> IO ()
bitwise a b = do
print $ a .&. b
print $ a .|. b
print $ a `xor` b
print $ complement a
print $ shiftL a b -- left shift
print $ shiftR a b -- arithmetic right shift
print $ shift a b -- You can also use the "unified" shift function; positive is for left shift, negative is for right shift
print $ shift a (-b)
print $ rotateL a b -- rotate left
print $ rotateR a b -- rotate right
print $ rotate a b -- You can also use the "unified" rotate function; positive is for left rotate, negative is for right rotate
print $ rotate a (-b)
main = bitwise 255 170

View file

@ -0,0 +1,11 @@
public static void bitwise(int a, int b){
System.out.println("a AND b: " + (a & b));
System.out.println("a OR b: "+ (a | b));
System.out.println("a XOR b: "+ (a ^ b));
System.out.println("NOT a: " + ~a);
System.out.println("a << b: " + (a << b)); // left shift
System.out.println("a >> b: " + (a >> b)); // arithmetic right shift
System.out.println("a >>> b: " + (a >>> b)); // logical right shift
System.out.println("a rol b: " + Integer.rotateLeft(a, b)); //rotate left, Java 1.5+
System.out.println("a ror b: " + Integer.rotateRight(a, b)); //rotate right, Java 1.5+
}

View file

@ -0,0 +1,4 @@
a <<= 3;
a = a << 3;
a *= 8; //2 * 2 * 2 = 8
a = a * 8;

View file

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

View file

@ -0,0 +1,65 @@
local bit = require"bit"
local vb = {
0, 1, -1, 2, -2, 0x12345678, 0x87654321,
0x33333333, 0x77777777, 0x55aa55aa, 0xaa55aa55,
0x7fffffff, 0x80000000, 0xffffffff
}
local function cksum(name, s, r)
local z = 0
for i=1,#s do z = (z + string.byte(s, i)*i) % 2147483629 end
if z ~= r then
error("bit."..name.." test failed (got "..z..", expected "..r..")", 0)
end
end
local function check_unop(name, r)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do s = s..","..tostring(f(x)) end
cksum(name, s, r)
end
local function check_binop(name, r)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do
for _,y in ipairs(vb) do s = s..","..tostring(f(x, y)) end
end
cksum(name, s, r)
end
local function check_binop_range(name, r, yb, ye)
local f = bit[name]
local s = ""
if pcall(f) or pcall(f, "z") or pcall(f, true) or pcall(f, 1, true) then
error("bit."..name.." fails to detect argument errors", 0)
end
for _,x in ipairs(vb) do
for y=yb,ye do s = s..","..tostring(f(x, y)) end
end
cksum(name, s, r)
end
local function check_shift(name, r)
check_binop_range(name, r, 0, 31)
end
-- Minimal sanity checks.
assert(0x7fffffff == 2147483647, "broken hex literals")
assert(0xffffffff == -1 or 0xffffffff == 2^32-1, "broken hex literals")
assert(tostring(-1) == "-1", "broken tostring()")
assert(tostring(0xffffffff) == "-1" or tostring(0xffffffff) == "4294967295", "broken tostring()")
-- Basic argument processing.
assert(bit.tobit(1) == 1)
assert(bit.band(1) == 1)
assert(bit.bxor(1,2) == 3)
assert(bit.bor(1,2,4,8,16,32,64,128) == 255)

View file

@ -0,0 +1,9 @@
function bitwiseOps(a,b)
disp(sprintf('%d and %d = %d', [a b bitand(a,b)]));
disp(sprintf('%d or %d = %d', [a b bitor(a,b)]));
disp(sprintf('%d xor %d = %d', [a b bitxor(a,b)]));
disp(sprintf('%d << %d = %d', [a b bitshift(a,b)]));
disp(sprintf('%d >> %d = %d', [a b bitshift(a,-b)]));
end

View file

@ -0,0 +1,6 @@
>> bitwiseOps(255,2)
255 and 2 = 2
255 or 2 = 255
255 xor 2 = 253
255 << 2 = 1020
255 >> 2 = 63

View file

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

View file

@ -0,0 +1,15 @@
use integer;
sub bitwise($$) {
($a, $b) = @_;
print 'a and b: '. ($a & $b) ."\n";
print 'a or b: '. ($a | $b) ."\n";
print 'a xor b: '. ($a ^ $b) ."\n";
print 'not a: '. (~$a) ."\n";
print 'a >> b: ', $a >> $b, "\n"; # logical right shift
use integer; # "use integer" enables bitwise operations to return signed ints
print "after use integer:\n";
print 'a << b: ', $a << $b, "\n"; # left shift
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift
}

View file

@ -0,0 +1,5 @@
: (& 6 3)
-> 2
: (& 7 3 1)
-> 1

View file

@ -0,0 +1,8 @@
: (bit? 1 2)
-> NIL
: (bit? 6 3)
-> NIL
: (bit? 6 15 255)
-> 6

View file

@ -0,0 +1,5 @@
: (| 1 2)
-> 3
: (| 1 2 4 8)
-> 15

View file

@ -0,0 +1,5 @@
: (x| 2 7)
-> 5
: (x| 2 7 1)
-> 4

View file

@ -0,0 +1,11 @@
: (>> 1 8)
-> 4
: (>> 3 16)
-> 2
: (>> -3 16)
-> 128
: (>> -1 -16)
-> -32

View file

@ -0,0 +1,7 @@
def bitwise(a, b):
print 'a and b:', a & b
print 'a or b:', a | b
print 'a xor b:', a ^ b
print 'not a:', ~a
print 'a << b:', a << b # left shift
print 'a >> b:', a >> b # arithmetic right shift

View file

@ -0,0 +1,8 @@
# 8-bit bounded shift:
x = x << n & 0xff
# ditto for 16 bit:
x = x << n & 0xffff
# ... and 32-bit:
x = x << n & 0xffffffff
# ... and 64-bit:
x = x << n & 0xffffffffffffffff

View file

@ -0,0 +1,41 @@
def bitstr(n, width=None):
"""return the binary representation of n as a string and
optionally zero-fill (pad) it to a given length
"""
result = list()
while n:
result.append(str(n%2))
n = int(n/2)
if (width is not None) and len(result) < width:
result.extend(['0'] * (width - len(result)))
result.reverse()
return ''.join(result)
def mask(n):
"""Return a bitmask of length n (suitable for masking against an
int to coerce the size to a given length)
"""
if n >= 0:
return 2**n - 1
else:
return 0
def rol(n, rotations=1, width=8):
"""Return a given number of bitwise left rotations of an integer n,
for a given bit field width.
"""
rotations %= width
if rotations < 1:
return n
n &= mask(width) ## Should it be an error to truncate here?
return ((n << rotations) & mask(width)) | (n >> (width - rotations))
def ror(n, rotations=1, width=8):
"""Return a given number of bitwise right rotations of an integer n,
for a given bit field width.
"""
rotations %= width
if rotations < 1:
return n
n &= mask(width)
return (n >> rotations) | ((n << (width - rotations)) & mask(width))

View file

@ -0,0 +1,5 @@
a <- as.hexmode(35)
b <- as.hexmode(42)
as.integer(a & b) # 34
as.integer(a | b) # 43
as.integer(xor(a, b)) # 9

View file

@ -0,0 +1,13 @@
intToLogicalBits <- function(intx) as.logical(intToBits(intx))
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb]))
"%AND%" <- function(x, y)
{
logicalBitsToInt(intToLogicalBits(x) & intToLogicalBits(y))
}
"%OR%" <- function(x, y)
{
logicalBitsToInt(intToLogicalBits(x) | intToLogicalBits(y))
}
35 %AND% 42 # 34
35 %OR% 42 # 42

View file

@ -0,0 +1,8 @@
library(bitops)
bitAnd(35, 42) # 34
bitOr(35, 42) # 43
bitXor(35, 42) # 9
bitFlip(35, bitWidth=8) # 220
bitShiftL(35, 1) # 70
bitShiftR(35, 1) # 17
# Note that no bit rotation is provided in this package

View file

@ -0,0 +1,14 @@
# As one can see from
getDLLRegisteredRoutines(getLoadedDLLs()$base)
# R knows functions bitwiseAnd, bitwiseOr, bitwiseXor and bitwiseNot.
# Here is how to call them (see ?.Call for the calling mechanism):
.Call("bitwiseOr", as.integer(12), as.integer(10))
.Call("bitwiseXor", as.integer(12), as.integer(10))
.Call("bitwiseAnd", as.integer(12), as.integer(10))
.Call("bitwiseNot", as.integer(12))
# It would be easy to embed these calls in R functions, for better readability
# Also, it's possible to call these functions on integer vectors:
.Call("bitwiseOr", c(5L, 2L), c(3L, 8L))

View file

@ -0,0 +1,35 @@
/*REXX program performs bitwise operations on integers: & | && ¬ «L »R */
numeric digits 1000 /*be able to handle bit integers.*/
say center('decimal',9) center("value",9) center('bits',50)
say copies('',9) copies('',9) copies('',50)
a = 21 ; call show a , 'A' /* show & tell A */
b = 3 ; call show b , 'B' /* show & tell B */
call show bAnd(a,b) , 'A & B' /* and */
call show bOr( a,b) , 'A | B' /* or */
call show bXOr(a,b) , 'A && B' /* xor */
call show bNot(a) , '¬ A' /* not */
call show bShiftL(a,b) , 'A [«B]' /* shift left */
call show bShiftR(a,b) , 'A [»B]' /* shirt right */
/*┌───────────────────────────────────────────────────────────────┐
Since REXX stores numbers (indeed, all values) as characters,
it makes no sense to "rotate" a value, since there aren't any
boundries for the value. I.E.: there isn't any 32bit word
"container" or "cell" (for instance) to store an integer.
*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────subroutines─────────────────────────*/
show: procedure; parse arg x,t; say right(x,9) center(t,9) right(d2b(x),50); return
d2b: return x2b(d2x(arg(1))) +0 /*some REXXes have the D2B bif.*/
b2d: return x2d(b2x(arg(1))) /*some REXXes have the B2D bif.*/
bNot: return b2d(translate(d2b(arg(1)), 10, 01)) +0 /*+0≡normalize.*/
bShiftL: return (b2d(d2b(arg(1)) || copies(0, arg(2)))) +0
bAnd: procedure; parse arg x,y; return c2d(bitand(d2c(x), d2c(y)))
bOr: procedure; parse arg x,y; return c2d(bitor( d2c(x), d2c(y)))
bXor: procedure; parse arg x,y; return c2d(bitxor(d2c(x), d2c(y)))
bShiftR: procedure; parse arg x,y; $=substr(reverse(d2b(x)), y+1)
if $=='' then $=0; return b2d(reverse($))

View file

@ -0,0 +1,9 @@
#lang racket
(define a 255)
(define b 5)
(list (bitwise-and a b)
(bitwise-ior a b)
(bitwise-xor a b)
(bitwise-not a)
(arithmetic-shift a b) ; left shift
(arithmetic-shift a (- b))) ; right shift

View file

@ -0,0 +1,8 @@
def bitwise(a, b)
puts "a and b: #{a & b}"
puts "a or b: #{a | b}"
puts "a xor b: #{a ^ b}"
puts "not a: #{~a}"
puts "a << b: #{a << b}" # left shift
puts "a >> b: #{a >> b}" # arithmetic right shift
end

View file

@ -0,0 +1,11 @@
def bitwise(a: Int, b: Int) {
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)) // unsigned right shift
println("a rot b: " + Integer.rotateLeft(a, b)) // Rotate Left
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right
}

View file

@ -0,0 +1,13 @@
(define (bitwise a b)
(display (bitwise-and a b))
(newline)
(display (bitwise-ior a b))
(newline)
(display (bitwise-xor a b))
(newline)
(display (bitwise-not a))
(newline)
(display (bitwise-arithmetic-shift-right a b))
(newline))
(bitwise 255 5)

View file

@ -0,0 +1,5 @@
5
255
250
-256
7

View file

@ -0,0 +1,10 @@
| testBitFunc |
testBitFunc := [ :a :b |
('%1 and %2 is %3' % { a. b. (a bitAnd: b) }) displayNl.
('%1 or %2 is %3' % { a. b. (a bitOr: b) }) displayNl.
('%1 xor %2 is %3' % { a. b. (a bitXor: b) }) displayNl.
('not %1 is %2' % { a. (a bitInvert) }) displayNl.
('%1 left shift %2 is %3' % { a. b. (a bitShift: b) }) displayNl.
('%1 right shift %2 is %3' % { a. b. (a bitShift: (b negated)) }) displayNl.
].
testBitFunc value: 16r7F value: 4 .

View file

@ -0,0 +1,8 @@
(a bitClear: b) "mask out bits"
(a bitAt: index) "retrieve a bit (bit-index, one-based)"
(a setBit: index) "set a bit (bit-index)"
(a clearBit: index) "clear a bit (bit-index)"
(a invertBit: index) "invert a bit (bit index)"
lowBit "find the index of the lowest one-bit; zero if none"
highBit "find the index of the highest one-bit; zero if none"
bitCount "count the one-bits"

View file

@ -0,0 +1,8 @@
proc bitwise {a b} {
puts [format "a and b: %#08x" [expr {$a & $b}]]
puts [format "a or b: %#08x" [expr {$a | $b}]]
puts [format "a xor b: %#08x" [expr {$a ^ $b}]]
puts [format "not a: %#08x" [expr {~$a}]]
puts [format "a << b: %#08x" [expr {$a << $b}]]
puts [format "a >> b: %#08x" [expr {$a >> $b}]]
}

View file

@ -0,0 +1,13 @@
proc bitwiseUnsupported {a b} {
set bits 0xFFFFFFFF
# Force interpretation as a 32-bit unsigned value
puts [format "a ArithRightShift b: %#08x" [expr {($a & $bits) >> $b}]]
puts [format "a RotateRight b: %#08x" [expr {
(($a >> $b) & ($bits >> $b)) |
(($a << (32-$b)) & ($bits ^ ($bits >> $b)))
}]]
puts [format "a RotateLeft b: %#08x" [expr {
(($a << $b) & $bits & ($bits << $b)) |
(($a >> (32-$b)) & ($bits ^ ($bits << $b)))
}]]
}