Bitwise operations: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 9:
If any operation is not available in your language, note it.
<br><br>
 
=={{header|11l}}==
{{trans|Kotlin}}
<syntaxhighlight lang="11l">V x = 10
V y = 2
print(‘x = ’x)
Line 37 ⟶ 36:
x ROR y = -2147483646
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Bitwise operations 15/02/2017
BITWISE CSECT
USING BITWISE,R13
Line 138 ⟶ 136:
Bitwise operations are done using the accumulator and an immediate constant (prefixed with #) or a value at a specified memory location (no #.)
 
<syntaxhighlight lang="6502asm">LDA #$05
STA temp ;temp equals 5 for the following</syntaxhighlight>
 
;AND
<syntaxhighlight lang="6502asm">LDA #$08
AND temp</syntaxhighlight>
 
;OR
<syntaxhighlight lang="6502asm">LDA #$08
ORA temp</syntaxhighlight>
 
;XOR
<syntaxhighlight lang="6502asm">LDA #$08
EOR temp</syntaxhighlight>
 
;NOT
<syntaxhighlight lang="6502asm">LDA #$08
EOR #255</syntaxhighlight>
 
The 6502 doesn't have arithmetic shift right, but it can be replicated, provided the negative flag is set according to the value in the accumulator.
<syntaxhighlight lang="6502asm"> 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
Line 167 ⟶ 165:
The 6502 can only rotate a value by one, not an arbitrary number. A looping routine is needed for rotates larger than 1.
Also, the 6502's <code>ROL</code> and <code>ROR</code> rotate instructions both rotate through the carry, unlike the instructions on other architectures with the same name. (68000, x86, and ARM all have a "ROR" command but it doesn't rotate through the carry on those CPUs.)
<syntaxhighlight lang="6502asm">LDA #$01
ROL ;if the carry was set prior to the ROL, A = 3. If the carry was clear, A = 2.</syntaxhighlight>
 
<syntaxhighlight lang="6502asm">LDA #$01
ROR ;if the carry was set prior to the ROR, A = 0x80. If clear, A = 0.</syntaxhighlight>
 
=={{header|68000 Assembly}}==
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation.
;AND
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0
MOVE.W #$200,D1
AND.W D0,D1</syntaxhighlight>
 
;OR
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0
MOVE.W #$200,D1
OR.W D0,D1</syntaxhighlight>
 
;XOR
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0
MOVE.W #$200,D1
EOR.W D0,D1</syntaxhighlight>
 
;NOT
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0
NOT.W D0</syntaxhighlight>
 
;Left Shift
<syntaxhighlight lang=68000devpac>MOVE.W #$FF,D0
MOVE.W #$04,D1
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</syntaxhighlight>
 
;Right Shift
<syntaxhighlight lang=68000devpac>MOVE.W #$FF,D0
MOVE.W #$04,D1
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</syntaxhighlight>
 
;Arithmetic Right Shift
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</syntaxhighlight>
 
;Left Rotate
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROL.W D1,D0</syntaxhighlight>
 
;Right Rotate
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROR.W D1,D0</syntaxhighlight>
 
;Left Rotate Through Extend Flag
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXL.W D1,D0</syntaxhighlight>
 
;Right Rotate Through Extend Flag
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXR.W D1,D0</syntaxhighlight>
 
=={{header|8051 Assembly}}==
Integer one is assumed to be a, integer two assumed to be b.
Line 234 ⟶ 175:
The end result of each operation resides in a.
The shift and rotate operations should likely push psw and pop psw because they affect the carry flag.
<syntaxhighlight lang="asm">; bitwise AND
anl a, b
 
Line 286 ⟶ 227:
rr a
djnz b, loop</syntaxhighlight>
 
=={{header|8086 Assembly}}==
;AND
<syntaxhighlight lang="asm">MOV AX,0345h
MOV BX,0444h
AND AX,BX</syntaxhighlight>
 
;OR
<syntaxhighlight lang="asm">MOV AX,0345h
MOV BX,0444h
OR AX,BX</syntaxhighlight>
 
;XOR
<syntaxhighlight lang="asm">MOV AX,0345h
MOV BX,0444h
XOR AX,BX</syntaxhighlight>
 
;NOT
<syntaxhighlight lang="asm">MOV AX,0345h
NOT AX</syntaxhighlight>
 
;Left Shift
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
SHL AX,CL</syntaxhighlight>
 
;Right Shift
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
SHR AX,CL</syntaxhighlight>
 
;Arithmetic Right Shift
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
SAR AX,CL</syntaxhighlight>
 
;Left Rotate
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
ROL AX,CL</syntaxhighlight>
 
;Right Rotate
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
ROR AX,CL</syntaxhighlight>
 
;Left Rotate Through Carry
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
RCL AX,CL</syntaxhighlight>
 
;Right Rotate Through Carry
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
RCR AX,CL</syntaxhighlight>
=={{header|68000 Assembly}}==
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation.
;AND
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0
MOVE.W #$200,D1
AND.W D0,D1</syntaxhighlight>
 
;OR
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0
MOVE.W #$200,D1
OR.W D0,D1</syntaxhighlight>
 
;XOR
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0
MOVE.W #$200,D1
EOR.W D0,D1</syntaxhighlight>
 
;NOT
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0
NOT.W D0</syntaxhighlight>
 
;Left Shift
<syntaxhighlight lang="68000devpac">MOVE.W #$FF,D0
MOVE.W #$04,D1
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</syntaxhighlight>
 
;Right Shift
<syntaxhighlight lang="68000devpac">MOVE.W #$FF,D0
MOVE.W #$04,D1
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</syntaxhighlight>
 
;Arithmetic Right Shift
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</syntaxhighlight>
 
;Left Rotate
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROL.W D1,D0</syntaxhighlight>
 
;Right Rotate
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROR.W D1,D0</syntaxhighlight>
 
;Left Rotate Through Extend Flag
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXL.W D1,D0</syntaxhighlight>
 
;Right Rotate Through Extend Flag
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXR.W D1,D0</syntaxhighlight>
=={{header|ABAP}}==
This works in ABAP 7.40 and above. The missing arithmetic shift operations have been implemented with arithmetic, whereas the logical shift and the rotate operations have been implemented using the built in string functions shift_left and shift_right.
 
<syntaxhighlight lang=ABAP"abap">
report z_bitwise_operations.
 
Line 639 ⟶ 633:
a rotr b -> C000003F, 11000000000000000000000000111111, -1073741761
</pre>
 
=={{header|ACL2}}==
Unlisted operations are not available
<syntaxhighlight lang=Lisp"lisp">(defun bitwise (a b)
(list (logand a b)
(logior a b)
Line 649 ⟶ 642:
(ash a b)
(ash a (- b))))</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">BYTE FUNC Not(BYTE a)
RETURN (a!$FF)
 
Line 685 ⟶ 677:
127 SHL 2 = 252
</pre>
 
=={{header|ActionScript}}==
ActionScript does not support bitwise rotations.
<syntaxhighlight lang=ActionScript"actionscript">function bitwise(a:int, b:int):void
{
trace("And: ", a & b);
Line 698 ⟶ 689:
trace("Right Shift(Logical): ", a >>> b);
}</syntaxhighlight>
 
=={{header|Ada}}==
The following program performs all required operations and prints the resulting values in base 2 for easy checking of the bit values.
 
<syntaxhighlight lang="ada">with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;
 
Line 725 ⟶ 715:
Put_Line (Unsigned_8'Image (Rotate_Right (X, N)));
end Bitwise;</syntaxhighlight>
 
=={{header|Aikido}}==
{{trans|Javascript}}
 
There is no rotate support built in to Aikido.
<syntaxhighlight lang="aikido">function bitwise(a, b){
println("a AND b: " + (a & b))
println("a OR b: "+ (a | b))
Line 739 ⟶ 728:
println("a >>> b: " + (a >>> b)) // logical right shift
}</syntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Standard - no extensions to language used}}
Line 747 ⟶ 735:
* 2r00000000000000000000000010101010, 4r0000000000002222, 8r00000000252, 16r000000aa
* and as an array of BOOL: FFFFFFFFFFFFFFFFFFFFFFFFTFTFTFTF
<syntaxhighlight lang="algol68">main:(
 
PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here #
Line 836 ⟶ 824:
</pre>
Note that an INT can be widened into BITS, and BITS can be widened into an array of BOOL. eg:
<syntaxhighlight lang="algol68"># unpack (widen) some data back into an a BOOL array #
INT i := 170;
BITS j := BIN i;
Line 854 ⟶ 842:
+85, 8r0125, FTFTFTFT
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">% 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 ) ;
Line 875 ⟶ 862:
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" )
end bitOPerations ;</syntaxhighlight>
 
=={{header|AppleScript}}==
Applescript has no bitwise operators. It's probably not the right tool to reach for if you need to work with bits.
Line 893 ⟶ 879:
 
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,264 ⟶ 1,250:
 
'''Second option''' – writing our own bitwise functions for Applescript:
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,771 ⟶ 1,757:
A '''third option''' is the mathematical one, although it still involves looping through the hypothetical bits where two numbers are involved, unless I've missed a trick. The handlers below all assume positive number inputs (except for ''arithmeticRightShift()'') and attempt to return results of class integer. The "hi bits" of numbers which don't fit the specified register sizes are discarded.
 
<syntaxhighlight lang="applescript">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.
Line 1,853 ⟶ 1,839:
rightRotate(92, 7, 8) --> 184
rightRotate(92, 7, 16) --> 47104</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
 
/* ARM assembly Raspberry PI */
Line 2,019 ⟶ 2,004:
 
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">a: 255
b: 2
 
Line 2,039 ⟶ 2,023:
255 SHL 2 = 1020
255 SHR 2 = 63 </pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey"autohotkey">bitwise(3, 4)
bitwise(a, b)
{
Line 2,051 ⟶ 2,034:
MsgBox % "a >> b: " . a >> b ; arithmetic right shift
}</syntaxhighlight>
 
=={{header|AutoIt}}==
No arithmetic shift.
<syntaxhighlight lang=AutoIt"autoit">bitwise(255, 5)
Func bitwise($a, $b)
MsgBox(1, '', _
Line 2,077 ⟶ 2,059:
255 ROL 5: 8160
255 ROR 5: 63495</pre>
 
=={{header|AWK}}==
Standard awk does not have bitwise operators. Gawk has built-in functions for many bitwise operations. No rotation of bits.
Line 2,083 ⟶ 2,064:
{{works with|gawk}}
 
<syntaxhighlight lang="awk">BEGIN {
n = 11
p = 1
Line 2,095 ⟶ 2,076:
 
[[OpenBSD]] <code>/usr/bin/awk</code> (a variant of [[nawk]]) has these same functions, with a few differences. Gawk uses 53-bit unsigned integers, but OpenBSD awk uses 32-bit signed integers. Therefore Gawk prints <code>not 11 = 0x1ffffffffffff4</code>, but OpenBSD awk prints <code>not 11 = 0xfffffff4</code>.
 
=={{header|Axe}}==
<syntaxhighlight lang="axe">Lbl BITS
r₁→A
r₂→B
Line 2,108 ⟶ 2,088:
 
Note that the symbols for AND, OR, and XOR are the stat plot marks near the bottom of the Catalog.
 
=={{header|Babel}}==
 
In Babel, we prefix the logic operators with a 'c' to denote that they are C-style operations, that is, they are word-width operations, not arbitrary size operations. The following program combines the numbers 5 and 9 using the various bitwise operators and then displays the results.
 
<syntaxhighlight lang="babel">({5 9}) ({cand} {cor} {cnor} {cxor} {cxnor} {shl} {shr} {ashr} {rol}) cart ! {give <- cp -> compose !} over ! {eval} over ! {;} each</syntaxhighlight>
 
{{Out}}
Line 2,128 ⟶ 2,107:
The cnot operator works on just one operand:
 
<syntaxhighlight lang="babel">9 cnot ;</syntaxhighlight>
 
{{Out}}
<pre>[val 0xfffffff6 ]</pre>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
QuickBasic does not have shift or rotate operations defined. Here are the logical operations:
<syntaxhighlight lang="qbasic">SUB bitwise (a, b)
PRINT a AND b
PRINT a OR b
Line 2,145 ⟶ 2,123:
{{works with|FreeBASIC}}
FreeBASIC does not have rotate operators. Shift Right operator performs arithmetic shift if the left value is signed number and logical shift if the left value is unsigned number.
<syntaxhighlight lang="freebasic">SUB bitwise (a AS Integer, b AS Integer)
DIM u AS UInteger
 
Line 2,161 ⟶ 2,139:
Commodore BASIC V2.0 does not have '''XOR''', '''left shift''', '''right shift''', '''right arithmetic shift''', '''left rotate''', and '''right rotate''' operators. In this implementation the '''XOR''' operation is done with an equivalent formula.
 
<syntaxhighlight lang="basic">10 INPUT "A="; A
20 INPUT "B="; B
30 PRINT "A AND B =" A AND B :rem AND
Line 2,178 ⟶ 2,156:
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang=IS"is-BASICbasic">100 LET A=10:LET B=12
110 PRINT A;"and";B;"=";A AND B
120 PRINT A;"band";B;"=";A BAND B
Line 2,193 ⟶ 2,171:
 
The disassembly of the Z80 code would be:
<syntaxhighlight lang="z80asm"> org 4084
3a 83 40 ld a, (4083)
47 ld b, a
Line 2,208 ⟶ 2,186:
Finally, observe that the first line reserves 15 bytes for our machine code routine by hiding them in a comment.
 
<syntaxhighlight lang="basic"> 10 REM ABCDEFGHIJKLMNO
20 INPUT A
30 INPUT B
Line 2,246 ⟶ 2,224:
Tiny BASIC has only one data type- the signed 16-bit integer- and no bitwise operations. This code emulates bitwise operations on unsigned 15-bit integers. Since the logic gates AND, NOR, and NXOR are characterised by having exactly two, exactly zero, and exactly one on bit in their inputs, their code is identical except for having a different number of target on bits (line 500 onward). The OR and XOR gates are just NOT NOR and NOT NXOR. The shift and rotate operations are simple divisions and mutiplications by 2, with care taken to avoid overflow, and a carry flag where applicable.
 
<syntaxhighlight lang="tinybasic">
REM VARIABLES
REM A = first number
Line 2,327 ⟶ 2,305:
GOTO 500
</syntaxhighlight>
 
=={{header|BASIC256}}==
<syntaxhighlight lang=BASIC256"basic256"># bitwise operators - floating point numbers will be cast to integer
a = 0b00010001
b = 0b11110000
Line 2,337 ⟶ 2,314:
print a | b # bitwise or on two integer values
print a & b # bitwise or on two integer values</syntaxhighlight>
 
=={{header|Batch File}}==
The SET command with the /A option supports arithmetic and bit operations on signed 8 byte integers.
Line 2,344 ⟶ 2,320:
 
The following script (bitops.bat) not only demonstrates the basic bit operations, it also uses bit operations to convert each integral value into a string of 32 binary digits.
<syntaxhighlight lang="dos">
@echo off
setlocal
Line 2,463 ⟶ 2,439:
11111101000000000000000000000001
</pre>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> number1% = &89ABCDEF
number2% = 8
Line 2,477 ⟶ 2,452:
PRINT ~ (number1% << number2%) OR (number1% >>> (32-number2%)) : REM left rotate
PRINT ~ (number1% >>> number2%) OR (number1% << (32-number2%)) : REM right rotate</syntaxhighlight>
 
=={{header|beeswax}}==
<syntaxhighlight lang="beeswax">#eX~T~T_#
###>N{` AND `~{~` = `&{Nz1~3J
UXe#
Line 2,506 ⟶ 2,480:
 
Example:
<syntaxhighlight lang=Julia"julia">
julia> beeswax("Bitops.bswx",0,0.0,Int(20000))
i9223653511831486512
Line 2,530 ⟶ 2,504:
 
Arithmetic shift right is not originally implemented in beeswax because it does not make sense for unsigned integers, but for negative numbers, it can be realized easily with
<syntaxhighlight lang="beeswax">A>>B = NOT(NOT(A)>>>B)</syntaxhighlight>
as demonstrated above.
 
In beeswax, rotate left (ROL) and rotate right (ROT) operators are implemented using modulo 64, so rotations by more than 63 bits wrap around:
 
<syntaxhighlight lang="beeswax">A ROL B = A<<(B%64)+A>>>(64-B%64)
A ROR B = A>>>(B%64)+A<<(64-B%64)</syntaxhighlight>
 
=={{header|Befunge}}==
<syntaxhighlight lang="befunge">> v MCR >v
1 2 3 4 5 6>61g-:| 8 9
>&&\481p >88*61p371p >:61g\`!:68*+71g81gp| 7 >61g2/61p71g1+71pv
Line 2,590 ⟶ 2,563:
1 22 23 106 42 10
</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">void bitwise(int a, int b)
{
printf("a and b: %d\n", a & b);
Line 2,608 ⟶ 2,580:
 
To rotate an integer, you can combine a left shift and a right shift:
<syntaxhighlight lang=C"c">/* rotate x to the right by s bits */
unsigned int rotr(unsigned int x, unsigned int s)
{
return (x >> s) | (x << 32 - s);
}</syntaxhighlight>With a smart enough compiler, the above actually compiles into a single machine bit rotate instruction when possible. E.g. <code>gcc -S</code> on IA32 produced following assembly code:<syntaxhighlight lang=Assembly"assembly">rotr:
movl 4(%esp), %eax ; arg1: x
movl 8(%esp), %ecx ; arg2: s
rorl %cl, %eax ; right rotate x by s
ret</syntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">static void bitwise(int a, int b)
{
Console.WriteLine("a and b is {0}", a & b);
Line 2,633 ⟶ 2,604:
// there are no rotation operators in C#
}</syntaxhighlight>
 
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <iostream>
 
void bitwise(int a, int b)
Line 2,659 ⟶ 2,629:
}</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="lisp">(bit-and x y)
(bit-or x y)
(bit-xor x y)
Line 2,668 ⟶ 2,637:
(bit-shift-right x n)
;;There is no built-in for rotation.</syntaxhighlight>
 
=={{header|COBOL}}==
Results are displayed in decimal.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. bitwise-ops.
 
Line 2,708 ⟶ 2,676:
 
{{works with|Visual COBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. mf-bitwise-ops.
Line 2,749 ⟶ 2,717:
GOBACK
.</syntaxhighlight>
 
=={{header|CoffeeScript}}==
CoffeeScript provides sugar for some JavaScript operators, but the bitwise operators are taken directly from JS. See more here: http://coffeescript.org/#operators
 
<syntaxhighlight lang="coffeescript">
f = (a, b) ->
p "and", a & b
Line 2,769 ⟶ 2,736:
 
output
<syntaxhighlight lang="text">
> coffee foo.coffee
and 2
Line 2,778 ⟶ 2,745:
>> 2
</syntaxhighlight>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defun bitwise (a b)
(print (logand a b)) ; AND
(print (logior a b)) ; OR ("ior" = inclusive or)
Line 2,792 ⟶ 2,758:
Left and right logical shift may be implemented by the following functions:
 
<syntaxhighlight lang="lisp">
(defun shl (x width bits)
"Compute bitwise left shift of x by 'bits' bits, represented on 'width' bits"
Line 2,806 ⟶ 2,772:
Left and right rotation may be implemented by the following functions:
 
<syntaxhighlight lang="lisp">
(defun rotl (x width bits)
"Compute bitwise left rotation of x by 'bits' bits, represented on 'width' bits"
Line 2,821 ⟶ 2,787:
(1- (ash 1 width)))))
</syntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">T rot(T)(in T x, in int shift) pure nothrow @nogc {
return (x >>> shift) | (x << (T.sizeof * 8 - shift));
}
Line 2,857 ⟶ 2,822:
 
Compilers are usually able to optimize the code pattern of the rot function to one CPU instruction plus loads. The DMD compiler too performs such optimization.
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">program Bitwise;
 
{$APPTYPE CONSOLE}
Line 2,873 ⟶ 2,837:
Readln;
end.</syntaxhighlight>
 
=={{header|DWScript}}==
<syntaxhighlight lang=Delphi"delphi">PrintLn('2 and 3 = '+IntToStr(2 and 3));
PrintLn('2 or 3 = '+IntToStr(2 or 3));
PrintLn('2 xor 3 = '+IntToStr(2 xor 3));
Line 2,881 ⟶ 2,844:
PrintLn('2 shl 3 = '+IntToStr(2 shl 3));
PrintLn('2 shr 3 = '+IntToStr(2 shr 3));</syntaxhighlight>
 
=={{header|E}}==
E provides arbitrary-size integers, so there is no distinct arithmetic and logical shift right. E does not provide bit rotate operations.
 
<syntaxhighlight lang="e">def bitwise(a :int, b :int) {
println(`Bitwise operations:
a AND b: ${a & b}
Line 2,895 ⟶ 2,857:
`)
}</syntaxhighlight>
 
=={{header|ECL}}==
<syntaxhighlight lang=ECL"ecl">
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION
BitAND := A & B;
Line 2,928 ⟶ 2,889:
*/
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
<syntaxhighlight lang="elena">import extensions;
 
extension testOp
Line 2,959 ⟶ 2,919:
255 shl 2 = 1020
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Bitwise_operation do
use Bitwise
Line 3,002 ⟶ 2,961:
255 >>> 2 = 63
</pre>
 
=={{header|Erlang}}==
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate.
 
<syntaxhighlight lang="erlang">
-module(bitwise_operations).
 
Line 3,023 ⟶ 2,981:
 
outputs:
<syntaxhighlight lang="erlang">
255 band 170 = 170
255 bor 170 = 255
Line 3,031 ⟶ 2,989:
255 bsr 170 = 0
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">let bitwise a b =
printfn "a and b: %d" (a &&& b)
printfn "a or b: %d" (a ||| b)
Line 3,042 ⟶ 2,999:
printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift
// No rotation operators.</syntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">"a=" "b=" [ write readln string>number ] bi@
{
[ bitand "a AND b: " write . ]
Line 3,055 ⟶ 3,011:
 
outputs:
<syntaxhighlight lang="factor">a=255
b=5
a AND b: 5
Line 3,064 ⟶ 3,020:
a asr b: 7</syntaxhighlight>
Currently rotation and logical shifts are not implemented.
 
=={{header|FALSE}}==
Only AND, OR, and NOT are available.
<syntaxhighlight lang="false">10 3
\$@$@$@$@\ { 3 copies }
"a & b = "&."
Line 3,073 ⟶ 3,028:
~a = "%~."
"</syntaxhighlight>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">: 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 .
Line 3,087 ⟶ 3,041:
2drop ;</syntaxhighlight>
Rotation is not standard, but may be provided in particular Forth implementations, or as an assembly instruction in CODE words.
 
=={{header|Fortran}}==
In ISO Fortran 90 and later the following BIT INTRINSIC functions are defined:
<syntaxhighlight lang="fortran">integer :: i, j = -1, k = 42
logical :: a
Line 3,118 ⟶ 3,071:
! arithmetically equivalent to: MOD((K / 2**7), 2**8)</syntaxhighlight>
The following INTRINSIC ELEMENTAL SUBROUTINE is also defined:
<syntaxhighlight lang="fortran"> 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</syntaxhighlight>
 
<syntaxhighlight lang="fortran">
program bits_rosetta
implicit none
Line 3,148 ⟶ 3,101:
</syntaxhighlight>
Output
<syntaxhighlight lang="text">
Input a= 14 b= 3
AND : 00000000000000000000000000001110 & 00000000000000000000000000000011 = 00000000000000000000000000000010 2
Line 3,158 ⟶ 3,111:
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823
</syntaxhighlight>
 
=={{header|Free Pascal}}==
<syntaxhighlight lang="pascal">program Bitwise;
{$mode objfpc}
var
Line 3,179 ⟶ 3,131:
Readln;
end.</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits)
 
Line 3,267 ⟶ 3,218:
x ROR y = 4611686018427387902
</pre>
 
=={{header|FutureBasic}}==
FB does not have a bitwise symbol for not, but rather uses the "not" expression. It does not support predefined bitwise symbols for rotate left and rotate right, but functions in this demo provide that capability.
<syntaxhighlight lang="futurebasic">window 1, @"Bitwise Operations", (0,0,650,270)
 
def fn rotl( b as long, n as long ) as long = ( ( 2^n * b) mod 256) or (b > 127)
Line 3,313 ⟶ 3,263:
Rotate right : fn rotr( a, b ) = 11000000000000000000000000111111 : -1073741761
</pre>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 3,366 ⟶ 3,315:
rol: 1000110100111111
ror: 1101001111111000</pre>
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">def bitwise = { a, b ->
println """
a & b = ${a} & ${b} = ${a & b}
Line 3,381 ⟶ 3,329:
 
Program:
<syntaxhighlight lang="groovy">bitwise(-15,3)</syntaxhighlight>
 
Output:
Line 3,391 ⟶ 3,339:
a >> b = -15 >> 3 = -2 arithmetic (sign-preserving) shift
a >>> b = -15 >>> 3 = 536870910 logical (zero-filling) shift</pre>
 
=={{header|Harbour}}==
Harbour language has a set of core functions, which are fully optimized
at compile time, to perform bitwise operations.
<syntaxhighlight lang="visualfoxpro">
PROCEDURE Main(...)
local n1 := 42, n2 := 2
Line 3,454 ⟶ 3,401:
Rotate left --> 168
Rotate right --> -2147483638
 
=={{header|Haskell}}==
 
The operations in ''Data.Bits'' work on ''Int'', ''Integer'', and any of the sized integer and word types.
<syntaxhighlight lang="haskell">import Data.Bits
 
bitwise :: Int -> Int -> IO ()
Line 3,500 ⟶ 3,446:
print $ shiftL (-1 :: Word) 1
print $ shiftR (-1 :: Word) 1
 
=={{header|HicEst}}==
There is no rotate and no shift support built in to HicEst
<syntaxhighlight lang="hicest">i = IAND(k, j)
i = IOR( k, j)
i = IEOR(k, j)
i = NOT( k )</syntaxhighlight>
 
=={{header|HPPPL}}==
<syntaxhighlight lang="hpppl">EXPORT BITOPS(a, b)
BEGIN
PRINT(BITAND(a, b));
Line 3,519 ⟶ 3,463:
// HPPPL has no builtin rotates or arithmetic right shift.
END;</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang=Icon"icon">procedure main()
bitdemo(255,2)
bitdemo(-15,3)
Line 3,565 ⟶ 3,508:
i shift 3: -120 = -1111000b
i shift -3: -2 = -10b</pre>
 
=={{header|Inform 6}}==
Inform 6 has no xor or rotate operators. It also has no shift operators, although the Z-machine, its usual target architecture, does. These can be accessed with inline assembly, which is done here.
 
<syntaxhighlight lang=Inform"inform 6">[ bitwise a b temp;
print "a and b: ", a & b, "^";
print "a or b: ", a | b, "^";
Line 3,585 ⟶ 3,527:
];
</syntaxhighlight>
 
=={{header|J}}==
 
Here are the "[http://www.jsoftware.com/help/dictionary/dbdotn.htm bitwise operators]":
 
<syntaxhighlight lang="j">bAND=: 17 b. NB. 16+#.0 0 0 1
bOR=: 23 b. NB. 16+#.0 1 1 1
bXOR=: 22 b. NB. 16+#.0 1 1 0
Line 3,602 ⟶ 3,543:
And here is a routine which takes a list of bitwise operators and two numbers and displays a table of results from combining those two numbers with each of the operators:
 
<syntaxhighlight lang="j">bitwise=: 1 :0
:
smoutput (((":x),"1' ',.(>u),.' '),"1":y),"1' => ',"1'.X'{~#:x u`:0 y
Line 3,609 ⟶ 3,550:
And here they are in action:
 
<syntaxhighlight lang="j"> 254 bAND`bOR`bXOR`b1NOT`bLshift`bRshift`bRAshift`bLrot`bRrot bitwise 3
254 bAND 3 => ............................X.
254 bOR 3 => ......................XXXXXXXX
Line 3,621 ⟶ 3,562:
 
Further test
<syntaxhighlight lang="j">
bXOR/ 3333 5555 7777 9999
8664
</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">public static void bitwise(int a, int b){
System.out.println("a AND b: " + (a & b));
System.out.println("a OR b: "+ (a | b));
Line 3,639 ⟶ 3,579:
}</syntaxhighlight>
All of the operators may be combined with the <tt>=</tt> operator to save space. For example, the following lines each do the same thing:
<syntaxhighlight lang="java">a <<= 3;
a = a << 3;
a *= 8; //2 * 2 * 2 = 8
a = a * 8;</syntaxhighlight>
 
=={{header|JavaScript}}==
There are no integers in Javascript, but there are still bitwise operators. They will convert their number operands into integers before performing they task. In other languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow and rarely used.
 
<syntaxhighlight lang="javascript">function bitwise(a, b){
alert("a AND b: " + (a & b));
alert("a OR b: "+ (a | b));
Line 3,656 ⟶ 3,595:
alert("a >>> b: " + (a >>> b)); // logical right shift
}</syntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia"># Version 5.2
@show 1 & 2 # AND
@show 1 | 2 # OR
Line 3,689 ⟶ 3,627:
rol(A,5) = Bool[true,true,false,false,true]
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">/* for symmetry with Kotlin's other binary bitwise operators
we wrap Java's 'rotate' methods as infix functions */
infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance)
Line 3,727 ⟶ 3,664:
x ROR y = -2147483646
</pre>
 
=={{header|LFE}}==
 
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate.
<syntaxhighlight lang="lisp">(defun bitwise (a b)
(lists:map
(lambda (x) (io:format "~p~n" `(,x)))
Line 3,760 ⟶ 3,696:
 
Example usage:
<syntaxhighlight lang="lisp">
> (bitwise 255 170)
170
Line 3,779 ⟶ 3,715:
>
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
Written as functions.
<syntaxhighlight lang="lb">
' bitwise operations on byte-sized variables
 
Line 3,830 ⟶ 3,765:
end function
</syntaxhighlight>
 
=={{header|Lingo}}==
Lingo has built-in functions for bitwise AND, OR, XOR and NOT:
<syntaxhighlight lang="lingo">put bitAND(2,7)
put bitOR(2,7)
put bitXOR(2,7)
put bitNOT(7)</syntaxhighlight>
Bit shifting and rotating has to be implemented by custom functions.
 
=={{header|LiveCode}}==
<syntaxhighlight lang=LiveCode"livecode">put "and:" && (255 bitand 2) & comma into bitops
put " or:" && (255 bitor 2) & comma after bitops
put " xor:" && (255 bitxor 2) & comma after bitops
Line 3,849 ⟶ 3,782:
and: 2, or: 255, xor: 253, not: 4294967040</syntaxhighlight>
LiveCode does not provide built-in bit-shift operations.
 
=={{header|LLVM}}==
<syntaxhighlight lang="llvm">; ModuleID = 'test.o'
;e means little endian
;p: { pointer size : pointer abi : preferred alignment for pointers }
Line 3,911 ⟶ 3,843:
;Declare external fuctions
declare i32 @printf(i8* nocapture, ...) nounwind</syntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<syntaxhighlight lang="logo">to bitwise :a :b
(print [a and b:] BitAnd :a :b)
(print [a or b:] BitOr :a :b)
Line 3,926 ⟶ 3,857:
bitwise 255 5</syntaxhighlight>
The output of this program is:
<syntaxhighlight lang="logo">a and b: 5
a or b: 255
a xor b: 250
Line 3,933 ⟶ 3,864:
a lshift -b: 7
-a ashift -b: -8</syntaxhighlight>
 
=={{header|LSE64}}==
{{incorrect|LSE64|No reason given.}}
<syntaxhighlight lang="lse64">over : 2 pick
2dup : over over
Line 3,947 ⟶ 3,877:
\ a \ 7 bitwise # hex literals</syntaxhighlight>
 
=={{header|Lua}}==
 
LuaBitOp implements bitwise functionality for Lua:
 
<syntaxhighlight lang="lua">local bit = require"bit"
 
local vb = {
Line 4,025 ⟶ 3,954:
==={{header|Lua 5.3+}}===
As of Lua 5.3 most of the required operations are built-in, and those still missing could be derived from them:
<syntaxhighlight lang="lua">a = 0xAA55AA55
b = 0x4
print(string.format("%8X and %8X = %16X", a, b, a&b))
Line 4,050 ⟶ 3,979:
AA55AA55 rol 4 = A55AA55A
AA55AA55 ror 4 = 5AA55AA5</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang=Maple"maple">
with(Bits):
bit:=proc(A,B)
Line 4,072 ⟶ 4,000:
end proc;
</syntaxhighlight>
 
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
Most functions are built-in or can be made really easily:
<syntaxhighlight lang=Mathematica"mathematica">(*and xor and or*)
BitAnd[integer1, integer2]
BitXor[integer1, integer2]
Line 4,094 ⟶ 4,021:
FromDigits[Prepend[Most[#], #[[1]]], 2] &[IntegerDigits[integer1, 2]]</syntaxhighlight>
The function BitShiftLeft, BitShiftRight, RotateRight, RotateLeft all take a second argument, which is the displacement, by default it is set to 1. BitAnd, BitXor and BitOr can handle more than 2 arguments:
<syntaxhighlight lang=Mathematica"mathematica">BitXor[3333, 5555, 7777, 9999]</syntaxhighlight>
gives back:
<syntaxhighlight lang=Mathematica"mathematica">8664</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Newer versions of MATLAB have even more bitwise operations than those demonstrated here. A complete list of bitwise operations for the newest version of MATLAB can be found at [http://www.mathworks.com/help/toolbox/fixedpoint/ref/f20333.html#bp7caxc-42 MathWorks]
 
<syntaxhighlight lang=MATLAB"matlab">function bitwiseOps(a,b)
 
disp(sprintf('%d and %d = %d', [a b bitand(a,b)]));
Line 4,112 ⟶ 4,038:
 
Output:
<syntaxhighlight lang=MATLAB"matlab">>> bitwiseOps(255,2)
255 and 2 = 2
255 or 2 = 255
Line 4,118 ⟶ 4,044:
255 << 2 = 1020
255 >> 2 = 63</syntaxhighlight>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">load(functs)$
 
a: 3661$
Line 4,143 ⟶ 4,068:
logand(a, -a - 1);
/* 0 */</syntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">fn bitwise a b =
(
format "a and b: %\n" (bit.and a b)
Line 4,158 ⟶ 4,082:
 
MAXScript doesn't have arithmetic shift or rotate operations.
 
=={{header|ML/I}}==
ML/I only supports bitwise AND and OR operations. These are available from version CKD onwards.
 
<syntaxhighlight lang=ML"ml/Ii">MCSKIP "WITH" NL
"" Bitwise operations
"" assumes macros on input stream 1, terminal on stream 2
Line 4,178 ⟶ 4,101:
*MCSET S10=2
</syntaxhighlight>
 
=={{header|Modula-3}}==
 
<syntaxhighlight lang="modula3">MODULE Bitwise EXPORTS Main;
 
IMPORT IO, Fmt, Word;
Line 4,215 ⟶ 4,137:
c RightRotate b: f8000007
</pre>
 
=={{header|Neko}}==
<syntaxhighlight lang=ActionScript"actionscript">/**
<doc>
<h2>bitwise operations</h2>
Line 4,299 ⟶ 4,220:
a ROL b: is not directly supported in Neko syntax
a ROR b: is not directly supported in Neko syntax</pre>
 
=={{header|Nemerle}}==
<syntaxhighlight lang=Nemerle"nemerle">def i = 255;
def j = 2;
 
Line 4,314 ⟶ 4,234:
// the operator performs a logical shift right
// there are no rotation operators in Nemerle, but you could define your own w/ a macro if you really wanted it</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc bitwise(a, b) =
echo "a and b: " , a and b
echo "a or b: ", a or b
Line 4,323 ⟶ 4,242:
echo "a << b: ", a shl b
echo "a >> b: ", a shr b</syntaxhighlight>
 
=={{header|NSIS}}==
All bitwise operations in NSIS are handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 IntOp] instruction.
<syntaxhighlight lang="nsis">Function Bitwise
Push $0
Push $1
Line 4,353 ⟶ 4,271:
Pop $0
FunctionEnd</syntaxhighlight>
 
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<syntaxhighlight lang="oberon2">
MODULE Bitwise;
IMPORT
Line 4,398 ⟶ 4,315:
a arithmetic right shift b :> 2
</pre>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">use IO;
 
bundle Default {
Line 4,417 ⟶ 4,333:
}
}</syntaxhighlight>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let bitwise a b =
Printf.printf "a and b: %d\n" (a land b);
Printf.printf "a or b: %d\n" (a lor b);
Line 4,428 ⟶ 4,343:
Printf.printf "a lsr b: %d\n" (a lsr b); (* logical right shift *)
;;</syntaxhighlight>
 
=={{header|Octave}}==
 
There's no arithmetic shift nor rotation (and the not can be done through a xor)
 
<syntaxhighlight lang="octave">function bitops(a, b)
s = sprintf("%s %%s %s = %%s\n", dec2bin(a), dec2bin(b));
printf(s, "or", dec2bin(bitor(a, b)));
Line 4,444 ⟶ 4,358:
 
bitops(0x1e, 0x3);</syntaxhighlight>
 
=={{header|Oforth}}==
 
There is no built-in for not and rotation
 
<syntaxhighlight lang=Oforth"oforth">: bitwise(a, b)
a b bitAnd println
a b bitOr println
Line 4,455 ⟶ 4,368:
a bitLeft(b) println
a bitRight(b) println ;</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx"oorexx">/* ooRexx *************************************************************
/ Bit Operations work as in Rexx (of course)
* Bit operations are performed up to the length of the shorter string.
Line 4,487 ⟶ 4,399:
a~bitor(b,p):001100110011010111111111 3335FF
</pre>
 
=={{header|OpenEdge/Progress}}==
 
The only bit operators available in OpenEdge are the GET-BITS() and PUT-BITS() functions. These functions can be used to implement all bitwise operators.
 
=={{header|PARI/GP}}==
Pari does not support bitwise rotations, which have no obvious meaning with arbitrary-precision integers. See also <code>bitnegimply</code> for another bitwise operator. For shifts, see also <code>shiftmul</code>.
<syntaxhighlight lang="parigp">bo(a,b)={
print("And: "bitand(a,b));
print("Or: "bitor(a,b));
Line 4,502 ⟶ 4,412:
print("Right shift: ",a>>b);
}</syntaxhighlight>
 
=={{header|Pascal}}==
While Standard Pascal does not have bitwise operations, most Pascal implementations (including Turbo Pascal and Delphi) extend the standard logical operators to also provide bitwise operations:
<syntaxhighlight lang="pascal">var
a, b: integer;
begin
Line 4,514 ⟶ 4,423:
writeln('a xor b = ', a xor b) { 6 = 0110 }
end.</syntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use integer;
sub bitwise($$) {
Line 4,531 ⟶ 4,439:
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift
}</syntaxhighlight>
 
=={{header|Phix}}==
Phix has four builtin bitwise operations (and/or/xor/not)_bits, which each have sequence and unsigned variants. Note careful use of latter (unsigned) routines here, since Phix naturally preserves signs (and common sense) when it can, rather than rudely treat, for instance, +4,294,967,295 as -1, unless explicitly told to do so as it is below. Likewise the builtin shift operators deliver signed and unbounded results, so we'll wrap them here. There are no builtin rotate routines, but easy enough to devise. The distributed copy (1.0.2+) also contains an (older) inline assembly version, which is obviously not JavaScript compatible, but may be significantly faster, for desktop-only applications.
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Bitwise_operations.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 4,586 ⟶ 4,493:
ror(10000000000000000000000011111110,111) = 11111101000000000000000000000001
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">6 var a 3 var b
 
def tab
Line 4,605 ⟶ 4,511:
"XOR = " print tab a b bitxor printBits
"NOT = " print tab a bitnot printBits</syntaxhighlight>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">function bitwise($a, $b)
{
function zerofill($a,$b) {
Line 4,622 ⟶ 4,527:
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
}</syntaxhighlight>
 
=={{header|PicoLisp}}==
PicoLisp has no specific word size. Numbers grow to arbitrary length. Therefore,
Line 4,629 ⟶ 4,533:
 
Bitwise AND:
<syntaxhighlight lang=PicoLisp"picolisp">: (& 6 3)
-> 2
 
Line 4,636 ⟶ 4,540:
Bitwise AND-Test (tests if all bits in the first argument are set in the
following arguments):
<syntaxhighlight lang=PicoLisp"picolisp">: (bit? 1 2)
-> NIL
 
Line 4,645 ⟶ 4,549:
-> 6</syntaxhighlight>
Bitwise OR:
<syntaxhighlight lang=PicoLisp"picolisp">: (| 1 2)
-> 3
 
Line 4,651 ⟶ 4,555:
-> 15</syntaxhighlight>
Bitwise XOR:
<syntaxhighlight lang=PicoLisp"picolisp">: (x| 2 7)
-> 5
 
Line 4,657 ⟶ 4,561:
-> 4</syntaxhighlight>
Shift (right with a positive count, left with a negative count):
<syntaxhighlight lang=PicoLisp"picolisp">: (>> 1 8)
-> 4
 
Line 4,668 ⟶ 4,572:
: (>> -1 -16)
-> -32</syntaxhighlight>
 
=={{header|Pike}}==
Rotate operations are not available
<syntaxhighlight lang=Pike"pike">
void bitwise(int a, int b)
{
Line 4,701 ⟶ 4,604:
a << b & 0xffffffff (32bit cap): 0xc0000000
</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">/* PL/I can perform bit operations on binary integers. */
k = iand(i,j);
k = ior(i,j);
Line 4,729 ⟶ 4,631:
u = substr(s, 2) || substr(s, 1, 1); /* implements rotate left. */
</syntaxhighlight>
 
=={{header|Pop11}}==
 
<syntaxhighlight lang="pop11">define bitwise(a, b);
printf(a && b, 'a and b = %p\n');
printf(a || b, 'a or b = %p\n');
Line 4,744 ⟶ 4,645:
 
Similarly, on infinitely precise numbers rotation is undefined.
 
=={{header|PowerShell}}==
Logical right shift and rotations are not supported in PowerShell.
{{works with|PowerShell|2.0}}
<syntaxhighlight lang=PowerShell"powershell">$X -band $Y
$X -bor $Y
$X -bxor $Y
Line 4,754 ⟶ 4,654:
{{works with|PowerShell|3.0}}
<syntaxhighlight lang=PowerShell"powershell">$X -shl $Y
# Arithmetic right shift
$X -shr $Y
Line 4,760 ⟶ 4,660:
# Requires quite a stretch of the imagination to call this "native" support of right rotate, but it works
[System.Security.Cryptography.SHA256Managed].GetMethod('RotateRight', 'NonPublic, Static', $null, @([UInt32], [Int32]), $null).Invoke($null, @([uint32]$X, $Y))</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Procedure Bitwise(a, b)
Debug a & b ; And
Debug a | b ;Or
Line 4,791 ⟶ 4,690:
Debug Temp
EndProcedure</syntaxhighlight>
 
=={{header|Python}}==
===Python 3===
Line 4,800 ⟶ 4,698:
binary output formatting in calculations and result displays.
 
<syntaxhighlight lang="python">def bitwise_built_ins(width, a, b):
mask = (1 << width) - 1
print(f"""\
Line 4,966 ⟶ 4,864:
 
===Python 2===
<syntaxhighlight lang="python">def bitwise(a, b):
print 'a and b:', a & b
print 'a or b:', a | b
Line 4,978 ⟶ 4,876:
Note: Newer Python versions (circa 2.4?) will automatically promote integers into "long integers" (arbitrary length, bounded by available memory). This can be noticed especially when using left shift operations. When using bitwise operations one usually wants to keep these bounded to specific sizes such as 8, 16, 32 or 64 bit widths. To do these we use the AND operator with specific values (bitmasks). For example:
 
<syntaxhighlight lang="python"># 8-bit bounded shift:
x = x << n & 0xff
# ditto for 16 bit:
Line 4,989 ⟶ 4,887:
We can easily implement our own rotation functions. For left rotations this is down by ORing the left shifted and masked lower bits against the right shifted upper bits. For right rotations we perform the converse operations, ORing a set of right shifted lower bits against the appropriate number of left shifted upper bits.
 
<syntaxhighlight lang="python">def bitstr(n, width=None):
"""return the binary representation of n as a string and
optionally zero-fill (pad) it to a given length
Line 5,032 ⟶ 4,930:
 
In this example we show a relatively straightforward function for converting integers into strings of bits, and another simple ''mask()'' function to create arbitrary lengths of bits against which we perform our masking operations. Also note that the implementation of these functions defaults to single bit rotations of 8-bit bytes. Additional arguments can be used to over-ride these defaults. Any case where the number of rotations modulo the width is zero represents a rotation of all bits back to their starting positions. This implementation should handle any integer number of rotations over bitfields of any valid (positive integer) length.
 
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
' no rotations and shift aritmetic are available in QB64
' Bitwise operator in Qbasic and QB64
Line 5,068 ⟶ 4,964:
 
</syntaxhighlight>
 
=={{header|Quackery}}==
 
Integers in Quackery are bignums, so the bitwise left rotate word <code>rot64</code> rotates specifically the least significant 64 bits of an integer. There is no corresponding bitwise right rotate, but it is readily defined from <code>rot64</code>.
 
<syntaxhighlight lang=Quackery"quackery"> [ [] swap
64 times
[ 2 /mod
Line 5,108 ⟶ 5,003:
bitwise RROTATE: 1111111111111110000000000000000000000000000000000000000000011111
</pre>
 
=={{header|R}}==
 
=== Native functions in R 3.x ===
<syntaxhighlight lang="rsplus"># Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd
 
a <- 35
Line 5,126 ⟶ 5,020:
 
===Using ''as.hexmode'' or ''as.octmode''===
<syntaxhighlight lang="rsplus">a <- as.hexmode(35)
b <- as.hexmode(42)
as.integer(a & b) # 34
Line 5,134 ⟶ 5,028:
===Using ''intToBits''===
The logical operators in R, namely &, | and !, are designed to work on logical vectors rather than bits. It is possible to convert from integer to logical vector and back to make these work as required, e.g.
<syntaxhighlight lang="rsplus">intToLogicalBits <- function(intx) as.logical(intToBits(intx))
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb]))
"%AND%" <- function(x, y)
Line 5,149 ⟶ 5,043:
 
===Using ''bitops'' package===
<syntaxhighlight lang="rsplus">library(bitops)
bitAnd(35, 42) # 34
bitOr(35, 42) # 43
Line 5,157 ⟶ 5,051:
bitShiftR(35, 1) # 17
# Note that no bit rotation is provided in this package</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define a 255)
Line 5,174 ⟶ 5,067:
'(5 255 250 -256 8160 7)
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2017.05}}
<syntaxhighlight lang="raku" line>constant MAXINT = uint.Range.max;
constant BITS = MAXINT.base(2).chars;
 
Line 5,230 ⟶ 5,122:
-65432 shift left 31: 1111111111111111100000000011010000000000000000000000000000000000
-65432 rotate left 31: 1111111111111111100000000011010001111111111111111111111111111111</pre>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red [Source: https://github.com/vazub/rosetta-red]
 
a: 10
Line 5,262 ⟶ 5,153:
a << b: 40
</pre>
 
=={{header|Retro}}==
There is no predefined arithmetic shifts in Retro.
 
<syntaxhighlight lang=Retro"retro">
: bitwise ( ab- )
cr
Line 5,278 ⟶ 5,168:
2over >> "a >> b = %d\n" puts
2drop ;</syntaxhighlight>
 
=={{header|REXX}}==
<pre>
Line 5,290 ⟶ 5,179:
╚═══════════════════════════════════════════════════════════════════════════════════════╝
</pre>
<syntaxhighlight lang="rexx">/*REXX program performs bit─wise operations on integers: & | && ¬ «L »R */
numeric digits 1000 /*be able to handle ginormous integers.*/
say center('decimal', 9) center("value", 9) center('bits', 50)
Line 5,326 ⟶ 5,215:
2 A [»B] 10
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
x = 8
y = 2
Line 5,339 ⟶ 5,227:
see "x >> y - Binary Right Shift : " + (x >> y) + nl
</syntaxhighlight>
 
=={{header|RLaB}}==
 
Line 5,345 ⟶ 5,232:
are integers then the result of the operation is an integer as well.
 
<syntaxhighlight lang=RLaB"rlab">>> x = int(3);
>> y = int(1);
>> z = x && y; printf("0x%08x\n",z); // logical 'and'
Line 5,358 ⟶ 5,245:
>> z = x / i2; printf("0x%08x\n",z); // right-shift is division by 2 where both arguments are integers
0x00000001</syntaxhighlight>
 
=={{header|Robotic}}==
<syntaxhighlight lang="robotic">
input string "First value"
set "local1" to "input"
Line 5,377 ⟶ 5,263:
. "Bitwise rotation is not natively supported"
</syntaxhighlight>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">def bitwise(a, b)
form = "%1$7s:%2$6d %2$016b"
puts form % ["a", a]
Line 5,404 ⟶ 5,289:
a >> b : 1 0000000000000001
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
let a: u8 = 105;
let b: u8 = 91;
Line 5,431 ⟶ 5,315:
a >> 3 = 00001101
</pre>
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">/* rotations are not available, but are easy to implement with the other bitwise operators */
data _null_;
a=105;
Line 5,445 ⟶ 5,328:
put _all_;
run;</syntaxhighlight>
 
=={{header|Scala}}==
 
<syntaxhighlight lang="scala">def bitwise(a: Int, b: Int) {
println("a and b: " + (a & b))
println("a or b: " + (a | b))
Line 5,459 ⟶ 5,341:
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right
}</syntaxhighlight>
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^6</math>RS}}
<syntaxhighlight lang="scheme">(import (rnrs arithmetic bitwise (6)))
 
(define (bitwise a b)
Line 5,478 ⟶ 5,359:
(bitwise 255 5)</syntaxhighlight>
Output:
<syntaxhighlight lang="text">5
255
250
Line 5,485 ⟶ 5,366:
 
''Note: bitwise operations were also described in [http://srfi.schemers.org/srfi-60/ SRFI-60], with additional aliases (and previously discussed in [http://srfi.schemers.org/srfi-33/ SRFI-33] which remained draft).''
 
=={{header|Seed7}}==
The type [http://seed7.sourceforge.net/manual/types.htm#integer integer] is intended for arithmetic operations.
Line 5,494 ⟶ 5,374:
Right shifting of bin32 values is done with logical shifts.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bin32.s7i";
 
Line 5,542 ⟶ 5,422:
a rolR b: 11010000000000000000001111111000
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func bitwise(a, b) {
say ('a and b : ', a & b)
say ('a or b : ', a | b)
Line 5,563 ⟶ 5,442:
a >> b : 1
</pre>
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
COMMENT TO MY KNOWLEDGE SIMULA DOES NOT SUPPORT BITWISE OPERATIONS SO WE MUST WRITE PROCEDURES FOR THE JOB ;
INTEGER WORDSIZE;
Line 5,678 ⟶ 5,556:
A ROTR B : -1073741823
</pre>
 
=={{header|Slate}}==
<syntaxhighlight lang="slate">[ |:a :b |
 
inform: (a bitAnd: b) printString.
Line 5,691 ⟶ 5,568:
] applyTo: {8. 12}.</syntaxhighlight>
'''Bold text'''
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
Line 5,697 ⟶ 5,573:
{{works with|VisualWorks Smalltalk}}
Since [[GNU Smalltalk]] by default runs without a graphical user interface, I wrote the program in that dialect. The actual methods for bitwise operations (''bitAnd:'', etc.) are the same in all implementations.
<syntaxhighlight lang="smalltalk">| testBitFunc |
testBitFunc := [ :a :b |
('%1 and %2 is %3' % { a. b. (a bitAnd: b) }) displayNl.
Line 5,710 ⟶ 5,586:
in addition to the above,
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">(a bitClear: b) "mask out bits"
(a bitAt: index) "retrieve a bit (bit-index, one-based)"
(a setBit: index) "set a bit (bit-index)"
Line 5,720 ⟶ 5,596:
 
Notice that all of those work on arbitrarily large integers (i.e. 1000 factorial lowBit -> 995).
 
=={{header|Standard ML}}==
For integers, IntInfs provide bitwise operations:
<syntaxhighlight lang="sml">fun bitwise_ints (a, b) = (
print ("a and b: " ^ IntInf.toString (IntInf.andb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n");
print ("a or b: " ^ IntInf.toString (IntInf.orb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n");
Line 5,732 ⟶ 5,607:
)</syntaxhighlight>
More shifts are available for words (unsigned ints):
<syntaxhighlight lang="sml">fun bitwise_words (a, b) = (
print ("a and b: " ^ Word.fmt StringCvt.DEC (Word.andb (a, b)) ^ "\n");
print ("a or b: " ^ Word.fmt StringCvt.DEC (Word.orb (a, b)) ^ "\n");
Line 5,741 ⟶ 5,616:
print ("a asr b: " ^ Word.fmt StringCvt.DEC (Word.>> (a, b) ) ^ "\n") (* logical right shift *)
)</syntaxhighlight>
 
=={{header|Stata}}==
Stata does not have bitwise operators as of version 15.1. It's possible to use Mata functions '''[https://www.stata.com/help.cgi?mf_inbase inbase]''' and '''frombase''' to convert integers to binary strings, and operate on these, but it will be much slower than native operators. William Matsuoka has written functions for this [http://www.wmatsuoka.com/stata/building-an-api-library here].
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">func bitwise(a: Int, b: Int) {
// All bitwise operations (including shifts)
// require both operands to be the same type
Line 5,771 ⟶ 5,644:
a lsr b: 2305843009213693950
</pre>
 
=={{header|SystemVerilog}}==
Verilog, being a hardware description language, had pretty comprehensive support for bit twiddling; though rotation is still a slightly manual operation. Just to be different, I decided to use a couple of 53-bit integers:
<syntaxhighlight lang=SystemVerilog"systemverilog">program main;
 
initial begin
Line 5,797 ⟶ 5,669:
If we want to do a variable bit rotation, then we need to think in hardware terms, and build a mux structure (this could be a function, but using a module allows it to be parameterized:
 
<syntaxhighlight lang=SystemVerilog"systemverilog">module rotate(in, out, shift);
 
parameter BITS = 32;
Line 5,811 ⟶ 5,683:
 
of course, one could always write the foreach loop inline.
 
=={{header|Tailspin}}==
Bytes values are infinitely extended to the left by sign extension when needed. The shift message can be used for all types of shifts, depending on the fill pattern which is infinitely repeated as needed to supply bits for vacated positions.
<syntaxhighlight lang="tailspin">
def a: [x f075 x];
def b: [x 81 x];
Line 5,840 ⟶ 5,711:
f075 rotated right 3 bits is be0e
</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">proc bitwise {a b} {
puts [format "a and b: %#08x" [expr {$a & $b}]]
puts [format "a or b: %#08x" [expr {$a | $b}]]
Line 5,851 ⟶ 5,721:
}</syntaxhighlight>
There are no built-in operations for arithmetic right shift or for bit rotation. Indeed, rotation precludes the use of arbitrary-width integers and can only be defined with respect to a particular width. However, we can simulate these operations for 32-bit values (requires Tcl 8.5):
<syntaxhighlight lang="tcl">proc bitwiseUnsupported {a b} {
set bits 0xFFFFFFFF
# Force interpretation as a 32-bit unsigned value
Line 5,864 ⟶ 5,734:
}]]
}</syntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
Line 5,871 ⟶ 5,740:
The right shift operation fills the new leftmost bit with a copy of the old leftmost bit.
 
<syntaxhighlight lang="ti89b">bitwise(a,b)
Prgm
Local show, oldbase
Line 5,894 ⟶ 5,763:
setMode("Base",oldbase)
EndPrgm</syntaxhighlight>
 
=={{header|Vala}}==
<syntaxhighlight lang=Vala"vala">void testbit(int a, int b) {
print(@"input: a = $a, b = $b\n");
print(@"AND: $a & $b = $(a & b)\n");
Line 5,922 ⟶ 5,790:
NOT: ~255 = -256
</pre>
 
=={{header|VBA}}==
In VBA, the logical operators And, Or, Xor, Not are actually binary operators. There are also Eqv and Imp (for bitwise "equivalence" and "logical implication").
 
<syntaxhighlight lang="vb">Debug.Print Hex(&HF0F0 And &HFF00) 'F000
Debug.Print Hex(&HF0F0 Or &HFF00) 'FFF0
Debug.Print Hex(&HF0F0 Xor &HFF00) 'FF0
Line 5,936 ⟶ 5,803:
The other operations in the task are not builtin, but are easy to implement. Integers are signed, and overflow throws and exception, one must take care of this.
 
<syntaxhighlight lang="vb">Function MaskL(k As Integer) As Long
If k < 1 Then
MaskL = 0
Line 6,018 ⟶ 5,885:
Examples
 
<syntaxhighlight lang="vb">Debug.Print Hex(MaskL(8)) 'FF000000
Debug.Print Hex(MaskR(8)) 'FF
Debug.Print Hex(Bit(7)) '80
Line 6,030 ⟶ 5,897:
Debug.Print Hex(RotateR(65535, -8)) 'FFFF00
</syntaxhighlight>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
identical syntax as in [[#VBA]].
 
=={{header|Visual Basic .NET}}==
<syntaxhighlight lang="vbnet">Sub Test(a as Integer, b as Integer)
WriteLine("And " & a And b)
WriteLine("Or " & a Or b)
Line 6,046 ⟶ 5,911:
 
Visual Basic doesn't have built-in support for bitwise rotation.
 
=={{header|Wren}}==
In Wren all numbers are represented in 64-bit floating point form.
Line 6,055 ⟶ 5,919:
 
Given this limitation, there is no difference between logical and arithmetic left and right shift operations. Although Wren doesn't support circular shift operators, it is not difficult to write functions to perform them.
<syntaxhighlight lang="ecmascript">var rl = Fn.new { |x, y| x << y | x >> (32-y) }
 
var rr = Fn.new { |x, y| x >> y | x << (32-y) }
Line 6,090 ⟶ 5,954:
x rr y = 2147483650
</pre>
 
=={{header|x86 Assembly}}==
{{works with|nasm}}
It must be linked with the libc and "start" code; lazyly a <tt>gcc bitops.o</tt> works, being bitops.o produced by <tt>nasm -f elf bitops.asm</tt> (I've chosen ELF since I am on a GNU/Linux box)
<syntaxhighlight lang="asm"> extern printf
global main
Line 6,198 ⟶ 6,061:
 
end</syntaxhighlight>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "bitwise"
 
Line 6,268 ⟶ 6,130:
10101 Rotr 11: 10100000000000000000000000000010
</pre>
 
=={{header|XLISP}}==
<syntaxhighlight lang="lisp">(defun bitwise-operations (a b)
; rotate operations are not supported
(print `(,a and ,b = ,(logand a b)))
Line 6,278 ⟶ 6,139:
(print `(,a right shift by ,b = ,(lsh a (- b)))) ; negative second operand shifts right
(print `(,a arithmetic right shift by ,b = ,(ash a (- b)))) )</syntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">Text(0, "A and B = "); HexOut(0, A and B); CrLf(0); \alternate symbol: &
Text(0, "A or B = "); HexOut(0, A or B); CrLf(0); \alternate symbol: !
Text(0, "A xor B = "); HexOut(0, A xor B); CrLf(0); \alternate symbol: |
Line 6,296 ⟶ 6,156:
operator was introduced at a time when only uppercase characters were
available (such as on the Apple II). The XOR operator was added later.
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">sub formBin$(n)
return right$("00000000" + bin$(n), 8)
end sub
Line 6,317 ⟶ 6,176:
XOR = 00000101
NOT 6 = 11111001</pre>
 
=={{header|Z80 Assembly}}==
;AND
<syntaxhighlight lang="z80">LD A,&05
AND &1F ;0x05 & 0x1F</syntaxhighlight>
 
;OR
<syntaxhighlight lang="z80">LD A,&05
OR &1F ;0x05 | 0x1F</syntaxhighlight>
 
;XOR
<syntaxhighlight lang="z80">LD A,&05
XOR &1F ;0x05 ^ 0x1F</syntaxhighlight>
 
;NOT
<syntaxhighlight lang="z80">LD A,&05
CPL</syntaxhighlight>
 
;Left Shift (Z80 can only shift by one at a time.)
<syntaxhighlight lang="z80">LD A,&05
SLA A</syntaxhighlight>
 
;Right Shift
<syntaxhighlight lang="z80">LD A,&05
SRL A</syntaxhighlight>
 
;Arithmetic Right Shift
<syntaxhighlight lang="z80">LD A,&05
SRA A</syntaxhighlight>
 
Line 6,351 ⟶ 6,209:
* <code>RLC/RRC</code> copies the bit "pushed out" to the carry but the old carry isn't rotated in.
 
<syntaxhighlight lang="z80">LD A,&05
RLA
 
Line 6,362 ⟶ 6,220:
LD A,&05
RRCA</syntaxhighlight>
 
 
 
=={{header|zkl}}==
No bitwise rotates. Shifts are unsigned.
<syntaxhighlight lang="zkl">(7).bitAnd(1) //-->1
(8).bitOr(1) //-->9
(7).bitXor(1) //-->6
Line 6,375 ⟶ 6,230:
(-1).toString(16) //-->ffffffffffffffff
(-1).shiftRight(1).toString(16) //-->7fffffffffffffff</syntaxhighlight>
 
 
{{omit from|bc|No built-in bitwise operations}}
{{omit from|dc|No built-in bitwise operations}}
10,327

edits