Bitwise operations: Difference between revisions

m
m (→‎{{header|6502 Assembly}}: fixed typos from copy-pasting)
 
(46 intermediate revisions by 24 users not shown)
Line 9:
If any operation is not available in your language, note it.
<br><br>
 
=={{header|11l}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="11l">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))
Line 23 ⟶ 22:
print(‘x SHR y = ’(x >> y))
print(‘x ROL y = ’rotl(x, y))
print(‘x ROR y = ’rotr(x, y))</langsyntaxhighlight>
{{out}}
<pre>
Line 39 ⟶ 38:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Bitwise operations 15/02/2017
BITWISE CSECT
USING BITWISE,R13
Line 120 ⟶ 119:
PG DS CL12
YREGS
END BITWISE</langsyntaxhighlight>
{{out}}
<pre>
Line 136 ⟶ 135:
</pre>
=={{header|6502 Assembly}}==
Bitwise operations are done using the accumulator and an immediate constant (prefixed with #) or a value at a specified memory location (no #.)
Integer one is in the accumulator, integer two is in zero page memory location "temp". Both are considered to be unsigned.
<lang 6502asm>AND temp ;ANDs accumulator with temp.
 
<syntaxhighlight lang="6502asm">LDA #$05
OR temp ;ORs accumulator with temp.
STA temp ;temp equals 5 for the following</syntaxhighlight>
 
;AND
EOR temp ;XORs accumulator with temp.
<syntaxhighlight lang="6502asm">LDA #$08
AND temp</syntaxhighlight>
 
;OR
EOR #$FF ;bitwise NOT on the accumulator.</lang>
<syntaxhighlight lang="6502asm">LDA #$08
ORA temp</syntaxhighlight>
 
;XOR
The 6502 can only shift left or right by one. Shifting by a variable number requires a loop.
<syntaxhighlight lang="6502asm">LDA #$08
There is also no arithmetic shift right on the 6502, only logical. It can also be replicated with a few commands.
EOR temp</syntaxhighlight>
 
;NOT
<lang 6502asm>multi_ASL:
<syntaxhighlight lang="6502asm">LDA #$08
LDX temp
EOR #255</syntaxhighlight>
CPX #$08
BNE loop_ASL
;although this is called "ASL" the name is misleading because it doesn't preserve the sign of bit 7!
;value will be zero anyway so don't bother
LDA #0
RTS
 
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.
loop_ASL:
<syntaxhighlight lang="6502asm"> LDA #$FF
ASL
CLC ;clear the carry. That way, ROR will not accidentally shift a 1 into the top bit of a positive number
DEX
BPL loop_ASLSKIP
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.
RTS
SKIP:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ROR</syntaxhighlight>
multi_LSR:
LDX temp
CPX #$08
BNE loop_LSR
;value will be zero anyway so don't bother
LDA #0
RTS
 
The 6502 can only rotate a value by one, not an arbitrary number. A looping routine is needed for rotates larger than 1.
loop_LSR:
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.)
LSR
<syntaxhighlight lang="6502asm">LDA #$01
DEX
ROL ;if the carry was set prior to the ROL, A = 3. If the carry was clear, A = 2.</syntaxhighlight>
BPL loop_LSR
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
multi_ASR
LDX temp
CPX #$08
BNE loop_ASR
;value will be either 0 or #$FF anyway so don't bother
PHA
PLA ;set the flags according to the accumulator
 
BMI returnFF
LDA #0
RTS
returnFF:
LDA #$FF
RTS
 
loop_ASR:
jsr ASR
DEX
BPL loop_ASR
RTS
 
ASR:
CLC ;clear the carry
PHA
PLA ;sets flags according to accumulator
BPL skip
SEC ;set the carry, the carry rotates into bit 7 during the ROR
skip:
ROR ;top bit will be the same as it was before.
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
multi_ROL:
LDX temp
loop_ROL:
ROL
DEX
BPL loop_ROL
RTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
multi_ROR:
LDX temp
loop_ROR:
ROR
DEX
BPL loop_ROR
RTS</lang>
 
<syntaxhighlight lang="6502asm">LDA #$01
ROR ;if the carry was set prior to the ROR, A = 0x80. If clear, A = 0.</syntaxhighlight>
=={{header|8051 Assembly}}==
Integer one is assumed to be a, integer two assumed to be b.
Line 229 ⟶ 176:
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.
<langsyntaxhighlight lang="asm">; bitwise AND
anl a, b
 
Line 280 ⟶ 227:
loop:
rr a
djnz b, loop</langsyntaxhighlight>
=={{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|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* 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"
 
</syntaxhighlight>
{{Out}}
<pre>
Result of And :
Register: 0000000000000000000000000000000000000000000000000000000000000101
Result of Or :
Register: 0000000000000000000000000000000000000000000000000000000000001111
Result of Exclusif Or :
Register: 0000000000000000000000000000000000000000000000000000000000001010
Result of Not :
Register: 1111111111111111111111111111111111111111111111111111111111111010
Result of left shift :
Register: 0000000000000000000000000000000000000000000000000000000000001010
Result of right shift :
Register: 0000000000000000000000000000000000000000000000000000000000000010
Result of Arithmetic right shift :
Register: 1111111111111111111111111111111111111111111111111111111111111011
Register: 1111111111111111111111111111111111111111111111111111111111111101
Result of rotate right :
Register: 1000000000000000000000000000000000000000000000000000000000000010
Result of Bit Clear :
Register: 0000000000000000000000000000000000000000000000000000000000001011
Register: 0000000000000000000000000000000000000000000000000000000000011001
</pre>
=={{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">
<lang ABAP>
report z_bitwise_operations.
 
Line 551 ⟶ 781:
new_value = result ).
write: |a rotr b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
</syntaxhighlight>
</lang>
 
{{output}}
Line 579 ⟶ 809:
a rotr b -> C000003F, 11000000000000000000000000111111, -1073741761
</pre>
 
=={{header|ACL2}}==
Unlisted operations are not available
<langsyntaxhighlight Lisplang="lisp">(defun bitwise (a b)
(list (logand a b)
(logior a b)
Line 588 ⟶ 817:
(lognot a)
(ash a b)
(ash a (- b))))</langsyntaxhighlight>
=={{header|Action!}}==
<syntaxhighlight lang="action!">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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bitwise_operations.png Screenshot from Atari 8-bit computer]
<pre>
127 AND 2 = 2
127 OR 2 = 127
127 XOR 2 = 125
NOT 127 = 128 (by 127 XOR $FF)
127 SHR 2 = 31
127 SHL 2 = 252
</pre>
=={{header|ActionScript}}==
ActionScript does not support bitwise rotations.
<langsyntaxhighlight ActionScriptlang="actionscript">function bitwise(a:int, b:int):void
{
trace("And: ", a & b);
Line 601 ⟶ 864:
trace("Right Shift(Arithmetic): ", a >> b);
trace("Right Shift(Logical): ", a >>> b);
}</langsyntaxhighlight>
 
=={{header|Ada}}==
The following program performs all required operations and prints the resulting values in base 2 for easy checking of the bit values.
 
<langsyntaxhighlight lang="ada">with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;
 
Line 628 ⟶ 890:
Put_Line (Unsigned_8'Image (Rotate_Left (X, N)));
Put_Line (Unsigned_8'Image (Rotate_Right (X, N)));
end Bitwise;</langsyntaxhighlight>
 
=={{header|Aikido}}==
{{trans|Javascript}}
 
There is no rotate support built in to Aikido.
<langsyntaxhighlight lang="aikido">function bitwise(a, b){
println("a AND b: " + (a & b))
println("a OR b: "+ (a | b))
Line 642 ⟶ 903:
println("a >> b: " + (a >> b)) // arithmetic right shift
println("a >>> b: " + (a >>> b)) // logical right shift
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Standard - no extensions to language used}}
Line 651 ⟶ 911:
* 2r00000000000000000000000010101010, 4r0000000000002222, 8r00000000252, 16r000000aa
* and as an array of BOOL: FFFFFFFFFFFFFFFFFFFFFFFFTFTFTFTF
<langsyntaxhighlight lang="algol68">main:(
 
PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here #
Line 714 ⟶ 974:
bitwise(16rff,16raa,5)
END CO
)</langsyntaxhighlight>
Output:
<pre> bits shorths: +1 1 plus the number of extra SHORT BITS types
Line 740 ⟶ 1,000:
</pre>
Note that an INT can be widened into BITS, and BITS can be widened into an array of BOOL. eg:
<langsyntaxhighlight lang="algol68"># unpack (widen) some data back into an a BOOL array #
INT i := 170;
BITS j := BIN i;
Line 752 ⟶ 1,012:
i := ABS j;
 
printf(($g", 8r"8r4d", "8(g)l$, i, j, k[bits width-8+1:]))</langsyntaxhighlight>
Output:
<pre>
Line 758 ⟶ 1,018:
+85, 8r0125, FTFTFTFT
</pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight 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 778 ⟶ 1,037:
write( n1, " shl ", n2, " = ", number( b1 shl n2 ), " ( left-shift )" );
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" )
end bitOPerations ;</langsyntaxhighlight>
 
=={{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 797 ⟶ 1,055:
 
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,151 ⟶ 1,409:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre>32 bit signed integers (in two's complement binary encoding)
Line 1,168 ⟶ 1,426:
 
'''Second option''' – writing our own bitwise functions for Applescript:
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,655 ⟶ 1,913:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre>32 bit signed integers (in two's complement binary encoding)
Line 1,675 ⟶ 1,933:
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.
 
<langsyntaxhighlight 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,756 ⟶ 2,014:
leftRotate(92, 7, 8) --> 46
rightRotate(92, 7, 8) --> 184
rightRotate(92, 7, 16) --> 47104</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 1,922 ⟶ 2,179:
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">a: 255
b: 2
 
Line 1,933 ⟶ 2,189:
print ["NOT" a "=" not a]
print [a "SHL" b "=" shl a b]
print [a "SHR" b "=" shr a b]</langsyntaxhighlight>
{{out}}
Line 1,943 ⟶ 2,199:
255 SHL 2 = 1020
255 SHR 2 = 63 </pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">bitwise(3, 4)
bitwise(a, b)
{
Line 1,954 ⟶ 2,209:
MsgBox % "a << b: " . a << b ; left shift
MsgBox % "a >> b: " . a >> b ; arithmetic right shift
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
No arithmetic shift.
<langsyntaxhighlight AutoItlang="autoit">bitwise(255, 5)
Func bitwise($a, $b)
MsgBox(1, '', _
Line 1,969 ⟶ 2,223:
$a & " ROL " & $b & ": " & BitRotate($a, $b) & @CRLF & _
$a & " ROR " & $b & ": " & BitRotate($a, $b * -1) & @CRLF )
EndFunc</langsyntaxhighlight>
{{out}}
Line 1,981 ⟶ 2,235:
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 1,987 ⟶ 2,240:
{{works with|gawk}}
 
<langsyntaxhighlight lang="awk">BEGIN {
n = 11
p = 1
Line 1,996 ⟶ 2,249:
print n " >> " p " = " rshift(n, p) # right shift
printf "not %d = 0x%x\n", n, compl(n) # bitwise complement
}</langsyntaxhighlight>
 
[[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}}==
<langsyntaxhighlight lang="axe">Lbl BITS
r₁→A
r₂→B
Line 2,009 ⟶ 2,261:
Disp "NOT:",not(A)ʳ▶Dec,i
.No language support for shifts or rotations
Return</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="babel">({5 9}) ({cand} {cor} {cnor} {cxor} {cxnor} {shl} {shr} {ashr} {rol}) cart ! {give <- cp -> compose !} over ! {eval} over ! {;} each</langsyntaxhighlight>
 
{{Out}}
Line 2,032 ⟶ 2,283:
The cnot operator works on just one operand:
 
<syntaxhighlight lang ="babel">9 cnot ;</langsyntaxhighlight>
 
{{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:
<langsyntaxhighlight lang="qbasic">SUB bitwise (a, b)
PRINT a AND b
PRINT a OR b
PRINT a XOR b
PRINT NOT a
END SUB</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight lang="freebasic">SUB bitwise (a AS Integer, b AS Integer)
DIM u AS UInteger
 
Line 2,060 ⟶ 2,310:
u = a
PRINT "a SHR b (logical) = "; u SHR b
END SUB</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
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.
 
<langsyntaxhighlight lang="basic">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</langsyntaxhighlight>
{{in}}
<pre>A=? 2
Line 2,082 ⟶ 2,332:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="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,089 ⟶ 2,339:
150 PRINT A;"xor";B;"=";XOR(A,B)
160 PRINT " not";A;"=";NOT A
170 DEF XOR(A,B)=(A BOR B)-(A BAND B)</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 2,097 ⟶ 2,347:
 
The disassembly of the Z80 code would be:
<langsyntaxhighlight lang="z80asm"> org 4084
3a 83 40 ld a, (4083)
47 ld b, a
Line 2,105 ⟶ 2,355:
06 00 ld b, 0
4f ld c, a ; value in BC reg pair is returned to BASIC
c9 ret</langsyntaxhighlight>
We then use <code>POKE</code> statements to replace the <code>and</code> instruction with each successive operation we want to perform.
 
Line 2,112 ⟶ 2,362:
Finally, observe that the first line reserves 15 bytes for our machine code routine by hiding them in a comment.
 
<langsyntaxhighlight lang="basic"> 10 REM ABCDEFGHIJKLMNO
20 INPUT A
30 INPUT B
Line 2,136 ⟶ 2,386:
230 POKE 16514,USR 16516
240 NEXT I
250 PRINT A;" << ";B;" = ";PEEK 16514</langsyntaxhighlight>
{{in}}
<pre>21
Line 2,150 ⟶ 2,400:
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.
 
<langsyntaxhighlight lang="tinybasic">
REM VARIABLES
REM A = first number
Line 2,230 ⟶ 2,480:
IF P = 0 THEN RETURN
GOTO 500
</syntaxhighlight>
</lang>
==={{header|uBasic/4tH}}===
{{trans|11l}}
uBasic/4tH provides the most common bitwise operations as functions. It's not too difficult to provide the arithmetic left and right shift operations.
<syntaxhighlight lang="uBasic/4tH">x = 10
y = 2
 
Print "x = "; x
Print "y = "; y
Print "NOT x = "; NOT(x)
Print "x AND y = "; AND(x, y)
Print "x OR y = "; OR(x, y)
Print "x XOR y = "; XOR(x, y)
Print "x SHL y = "; SHL(x, y)
Print "x SHR y = "; SHL(x, -y)
Print "x ROL y = "; FUNC(_rotl (x, y))
Print "x ROR y = "; FUNC(_rotr (x, y))
 
End
 
_rotr Param (2) : Return (OR(SHL(a@, -b@), SHL(a@, Info("wordsize")-b@)))
_rotl Param (2) : Return (OR(SHL(a@, b@), SHL(a@, -Info("wordsize")+b@)))</syntaxhighlight>
{{Out}}
<pre>x = 10
y = 2
NOT x = -11
x AND y = 2
x OR y = 10
x XOR y = 8
x SHL y = 40
x SHR y = 2
x ROL y = 40
x ROR y = -9223372036854775806
 
0 OK, 0:320</pre>
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256"># bitwise operators - floating point numbers will be cast to integer
a = 0b00010001
b = 0b11110000
Line 2,240 ⟶ 2,524:
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</langsyntaxhighlight>
 
=={{header|Batch File}}==
The SET command with the /A option supports arithmetic and bit operations on signed 8 byte integers.
Line 2,248 ⟶ 2,531:
 
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.
<langsyntaxhighlight lang="dos">
@echo off
setlocal
Line 2,322 ⟶ 2,605:
)
exit /b
</syntaxhighlight>
</lang>
 
Sample output
Line 2,367 ⟶ 2,650:
11111101000000000000000000000001
</pre>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> number1% = &89ABCDEF
number2% = 8
Line 2,380 ⟶ 2,662:
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</langsyntaxhighlight>
 
=={{header|beeswax}}==
<langsyntaxhighlight lang="beeswax">#eX~T~T_#
###>N{` AND `~{~` = `&{Nz1~3J
UXe#
Line 2,407 ⟶ 2,688:
###
>UX`-`!P{M!` >> `~{~` = `!)!`-`M!{` , interpreted as (negative) signed Int64 number (MSB=1)`NN;
#>e#</langsyntaxhighlight>
 
Example:
<syntaxhighlight lang="julia">
<lang Julia>
julia> beeswax("Bitops.bswx",0,0.0,Int(20000))
i9223653511831486512
Line 2,429 ⟶ 2,710:
logical shift right, and negating the result again:
 
-9223090561878065104 >> 48 = -32767 , interpreted as (negative) signed Int64 number (MSB=1)</langsyntaxhighlight>
 
The natural number range for beeswax is unsigned Int64, but it is easy to implement signed Int64 by realizing negative numbers by their 2’s complements or interpreting numbers as negative if their MSB is 1, as shown in the example above.
 
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
<langsyntaxhighlight lang="beeswax">A>>B = NOT(NOT(A)>>>B)</langsyntaxhighlight>
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:
 
<langsyntaxhighlight lang="beeswax">A ROL B = A<<(B%64)+A>>>(64-B%64)
A ROR B = A>>>(B%64)+A<<(64-B%64)</langsyntaxhighlight>
 
=={{header|Befunge}}==
<langsyntaxhighlight 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,465 ⟶ 2,745:
^ < G
 
</syntaxhighlight>
</lang>
The labelled points (1 to G) are:
1. Read in A and B,
Line 2,494 ⟶ 2,774:
1 22 23 106 42 10
</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">void bitwise(int a, int b)
{
printf("a and b: %d\n", a & b);
Line 2,509 ⟶ 2,788:
/* there are no rotation operators in C */
return 0;
}</langsyntaxhighlight>
 
To rotate an integer, you can combine a left shift and a right shift:
<langsyntaxhighlight Clang="c">/* rotate x to the right by s bits */
unsigned int rotr(unsigned int x, unsigned int s)
{
return (x >> s) | (x << 32 - s);
}</langsyntaxhighlight>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:<langsyntaxhighlight Assemblylang="assembly">rotr:
movl 4(%esp), %eax ; arg1: x
movl 8(%esp), %ecx ; arg2: s
rorl %cl, %eax ; right rotate x by s
ret</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">static void bitwise(int a, int b)
{
Console.WriteLine("a and b is {0}", a & b);
Line 2,536 ⟶ 2,814:
// the operator performs a logical shift right
// there are no rotation operators in C#
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{trans|C}}
<langsyntaxhighlight lang="cpp">#include <iostream>
 
void bitwise(int a, int b)
Line 2,548 ⟶ 2,825:
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 cua = a;
std::cout << "ca sralsr b: " << (cua >> b) << '\n'; // logical right shift (guaranteed)
// there are no rotation operators in C++
}</lang>
 
// 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';
}</syntaxhighlight>
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(bit-and x y)
(bit-or x y)
(bit-xor x y)
Line 2,562 ⟶ 2,847:
(bit-shift-left x n)
(bit-shift-right x n)
;;There is no built-in for rotation.</langsyntaxhighlight>
 
=={{header|COBOL}}==
{{Works with|COBOL 2023}}
Results are displayed in decimal.
COBOL 2002 added support for bitwise operations. Shift and rotation operators were added in COBOL 2023. Results are displayed in decimal.
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. bitwise-ops.
 
Line 2,573 ⟶ 2,858:
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.
PIC S9(9) USAGE COMPUTATIONAL.
 
LINKAGE SECTION.
01 a-int USAGE BINARY-LONG.
Line 2,597 ⟶ 2,881:
DISPLAY "a exclusive-or b is " result-disp
 
*> More complex *> COBOL does notoperations havecan shiftbe orconstructed rotationfrom operatorsthese.
 
GOBACKCOMPUTE result = B-NOT (a B-XOR b)
DISPLAY "Logical equivalence of a and b is " result-disp
.</lang>
 
COMPUTE result = (B-NOT a) B-AND b
DISPLAY "Logical implication of a and b is " result-disp
 
*> Shift and rotation operators were only added in COBOL 2023.
 
COMPUTE result = a B-SHIFT-L b
DISPLAY "a shifted left by b is " result-disp
 
COMPUTE result = b B-SHIFT-R a
DISPLAY "b shifted right by a is " result-disp
 
COMPUTE result = a B-SHIFT-LC b
DISPLAY "a rotated left by b is " result-disp
 
COMPUTE result = b B-SHIFT-RC a
DISPLAY "b rotated right by a is " result-disp
 
GOBACK.
 
END PROGRAM bitwise-ops.</syntaxhighlight>
 
{{works with|GnuCOBOL}}
{{works with|Visual COBOL}}
In older implementations, non-standard extensions were developed as built-in subroutines.
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> 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.
Line 2,621 ⟶ 2,927:
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.
 
.</lang>
END PROGRAM mf-bitwise-ops.</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
 
<langsyntaxhighlight lang="coffeescript">
f = (a, b) ->
p "and", a & b
Line 2,661 ⟶ 2,968:
 
f(10,2)
</syntaxhighlight>
</lang>
 
output
<syntaxhighlight lang="text">
> coffee foo.coffee
and 2
Line 2,672 ⟶ 2,979:
<< 40
>> 2
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun bitwise (a b)
(print (logand a b)) ; AND
(print (logior a b)) ; OR ("ior" = inclusive or)
Line 2,683 ⟶ 2,989:
(print (ash a (- b))) ; arithmetic right shift (negative 2nd arg)
; no logical shift
)</langsyntaxhighlight>
 
Left and right logical shift may be implemented by the following functions:
 
<langsyntaxhighlight lang="lisp">
(defun shl (x width bits)
"Compute bitwise left shift of x by 'bits' bits, represented on 'width' bits"
Line 2,697 ⟶ 3,003:
(logand (ash x (- bits))
(1- (ash 1 width))))
</syntaxhighlight>
</lang>
 
Left and right rotation may be implemented by the following functions:
 
<langsyntaxhighlight lang="lisp">
(defun rotl (x width bits)
"Compute bitwise left rotation of x by 'bits' bits, represented on 'width' bits"
Line 2,715 ⟶ 3,021:
(logand (ash x (- width (mod bits width)))
(1- (ash 1 width)))))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">T rot(T)(in T x, in int shift) pure nothrow @nogc {
return (x >>> shift) | (x << (T.sizeof * 8 - shift));
}
Line 2,740 ⟶ 3,045:
 
testBit(a, b);
}</langsyntaxhighlight>
{{out}}
<pre>Input: a = 255, b = 2
Line 2,752 ⟶ 3,057:
 
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}}==
<langsyntaxhighlight Delphilang="delphi">program Bitwise;
 
{$APPTYPE CONSOLE}
Line 2,767 ⟶ 3,071:
// there are no built-in rotation operators in Delphi
Readln;
end.</langsyntaxhighlight>
 
=={{header|DWScript}}==
<langsyntaxhighlight Delphilang="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));
PrintLn('not 2 = '+IntToStr(not 2));
PrintLn('2 shl 3 = '+IntToStr(2 shl 3));
PrintLn('2 shr 3 = '+IntToStr(2 shr 3));</langsyntaxhighlight>
 
=={{header|E}}==
E provides arbitrary-size integers, so there is no distinct arithmetic and logical shift right. E does not provide bit rotate operations.
 
<langsyntaxhighlight lang="e">def bitwise(a :int, b :int) {
println(`Bitwise operations:
a AND b: ${a & b}
Line 2,789 ⟶ 3,091:
a right shift b: ${a >> b}
`)
}</langsyntaxhighlight>
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
# 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
</syntaxhighlight>
 
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
<lang ECL>
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION
BitAND := A & B;
Line 2,822 ⟶ 3,136:
*/
</syntaxhighlight>
</lang>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
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())}
|
);
}
}
}
</syntaxhighlight>
 
Results in (extracted for just one of the test values):
{{out}}
<pre>
For values 1 (0x01) and 5 (0x05):
0x01 AND 0x05 = 0x01
0x01 OR 0x05 = 0x05
0x01 XOR 0x05 = 0x04
NOT 0x01 = 0xFFFFFFFFFFFFFFFE
left shift 0x01 by 5 = 0x20
right shift 0x01 by 5 = 0x00
right arithmetic shift 0x01 by 5 = 0x00
left rotate 0x01 by 5 = 0x20
right rotate 0x01 by 5 = 0x0800000000000000
leftmost bit of 0x01 = 0x01
rightmost bit of 0x01 = 0x01
leading zero count of 0x01 = 63
trailing zero count of 0x01 = 0
bit count (aka "population") of 0x01 = 1
reversed bits of 0x01 = 0x8000000000000000
reverse bytes of 0x01 = 0x0100000000000000
</pre>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
 
extension testOp
Line 2,832 ⟶ 3,203:
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.InvertedBInverted);
console.printLine(self," shr ",y," = ",self.shiftRight(y));
console.printLine(self," shl ",y," = ",self.shiftLeft(y));
Line 2,844 ⟶ 3,215:
{
console.loadLineTo(new Integer()).bitwiseTest(console.loadLineTo(new Integer()))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,856 ⟶ 3,227:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Bitwise_operation do
use Bitwise
Line 2,877 ⟶ 3,248:
end
 
Bitwise_operation.test</langsyntaxhighlight>
 
{{out}}
Line 2,897 ⟶ 3,268:
255 >>> 2 = 63
</pre>
 
=={{header|Erlang}}==
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate.
 
<langsyntaxhighlight lang="erlang">
-module(bitwise_operations).
 
Line 2,915 ⟶ 3,285:
io:format("~p bsl ~p = ~p\n",[A,B,A bsl B]),
io:format("~p bsr ~p = ~p\n",[A,B,A bsr B]).
</syntaxhighlight>
</lang>
 
outputs:
<langsyntaxhighlight lang="erlang">
255 band 170 = 170
255 bor 170 = 255
Line 2,925 ⟶ 3,295:
255 bsl 170 = 381627307539845370001346183518875822092557105621893120
255 bsr 170 = 0
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let bitwise a b =
printfn "a and b: %d" (a &&& b)
printfn "a or b: %d" (a ||| b)
Line 2,936 ⟶ 3,305:
printfn "a shr b: %d" (a >>> b) // arithmetic shift
printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift
// No rotation operators.</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">"a=" "b=" [ write readln string>number ] bi@
{
[ bitand "a AND b: " write . ]
Line 2,947 ⟶ 3,315:
[ abs shift "a asl b: " write . ]
[ neg shift "a asr b: " write . ]
} 2cleave</langsyntaxhighlight>
 
outputs:
<langsyntaxhighlight lang="factor">a=255
b=5
a AND b: 5
Line 2,957 ⟶ 3,325:
NOT a: -256
a asl b: 8160
a asr b: 7</langsyntaxhighlight>
Currently rotation and logical shifts are not implemented.
 
=={{header|FALSE}}==
Only AND, OR, and NOT are available.
<langsyntaxhighlight lang="false">10 3
\$@$@$@$@\ { 3 copies }
"a & b = "&."
a | b = "|."
~a = "%~."
"</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight 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 2,980 ⟶ 3,346:
cr ." a shr b = " 2dup rshift .
cr ." a ashr b = " 2dup arshift .
2drop ;</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="fortran">integer :: i, j = -1, k = 42
logical :: a
Line 3,011 ⟶ 3,376:
! 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)</langsyntaxhighlight>
The following INTRINSIC ELEMENTAL SUBROUTINE is also defined:
<langsyntaxhighlight 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</langsyntaxhighlight>
 
<langsyntaxhighlight lang="fortran">
program bits_rosetta
implicit none
Line 3,041 ⟶ 3,406:
 
end program bits_rosetta
</syntaxhighlight>
</lang>
Output
<syntaxhighlight lang="text">
Input a= 14 b= 3
AND : 00000000000000000000000000001110 & 00000000000000000000000000000011 = 00000000000000000000000000000010 2
Line 3,052 ⟶ 3,417:
NOT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11111111111111111111111111110001 -15
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823
</syntaxhighlight>
</lang>
 
=={{header|Free Pascal}}==
<langsyntaxhighlight lang="pascal">program Bitwise;
{$mode objfpc}
var
Line 3,073 ⟶ 3,437:
writeln('2 sar 3 = ', sarshortint(x,y));
Readln;
end.</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits)
 
Line 3,146 ⟶ 3,509:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 3,162 ⟶ 3,525:
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)
<lang futurebasic>
include "ConsoleWindow"
 
def fn rotl( b as long, n as long ) as long = ( ( 2^n * b) mod 256) or (b > 127)
// Set tab width for printing
def fn rotr( b as long, n as long ) as long = (b >> n mod 32) or ( b << (32-n) mod 32)
def tab 1
 
local fn rotl( b as long, n as long ) as long
end fn = ( ( 2^n * b) mod 256) or (b > 127)
 
local fn rotr( b as long, n as long ) as long
end fn = (b >> n mod 32) or ( b << (32-n) mod 32)
 
local fn bitwise( a as long, b as long )
print @"Input: a = "; a; @" b = "; b
print
print @"AND :", @"a && b = ", bin$(a && b), @": "; a && b
print @"NAND :", @"a ^& b = ", bin$(a ^& b), @": "; a ^& b
print @"OR :", @"a || b = ", bin$(a || b), @": "; a || b
print @"NOR :", @"a ^| b = ", bin$(a ^| b), @": "; a ^| b
print @"XOR :", @"a ^^ b = ", bin$(a ^^ b), @": "; a ^^ b
print @"NOT :", @" not a = ", bin$( not a), @": "; not a
print
print @"Left shift :", @"a << b =", bin$(a << b), @": "; a << b
print @"Right shift :", @"a >> b =", bin$(a >> b), @": "; a >> b
print
print @"Rotate left :", @"fn rotl( a, b ) = ", bin$(fn rotl( a, b)), @": "; fn rotl( a, b )
print @"Rotate right :", @"fn rotr( a, b ) = ", bin$(fn rotr( a, b )),@": "; fn rotr( a, b )
end fn
 
fn bitwise( 255, 2 )
 
</lang>
HandleEvents</syntaxhighlight>
 
Output:
Line 3,214 ⟶ 3,570:
Rotate right : fn rotr( a, b ) = 11000000000000000000000000111111 : -1073741761
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 3,253 ⟶ 3,608:
var a, b int16 = -460, 6
bitwise(a, b)
}</langsyntaxhighlight>
Output:
<pre>a: 1111111000110100
Line 3,267 ⟶ 3,622:
rol: 1000110100111111
ror: 1101001111111000</pre>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def bitwise = { a, b ->
println """
a & b = ${a} & ${b} = ${a & b}
Line 3,279 ⟶ 3,633:
a >>> b = ${a} >>> ${b} = ${a >>> b} logical (zero-filling) shift
"""
}</langsyntaxhighlight>
 
Program:
<syntaxhighlight lang ="groovy">bitwise(-15,3)</langsyntaxhighlight>
 
Output:
Line 3,292 ⟶ 3,646:
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.
<langsyntaxhighlight lang="visualfoxpro">
PROCEDURE Main(...)
local n1 := 42, n2 := 2
Line 3,340 ⟶ 3,693:
return
 
</syntaxhighlight>
</lang>
Output:
Bitwise operations with two integers
Line 3,355 ⟶ 3,708:
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.
<langsyntaxhighlight lang="haskell">import Data.Bits
 
bitwise :: Int -> Int -> IO ()
Line 3,382 ⟶ 3,734:
 
main :: IO ()
main = bitwise 255 170</langsyntaxhighlight>
{{Out}}
<pre>170
Line 3,401 ⟶ 3,753:
print $ shiftL (-1 :: Word) 1
print $ shiftR (-1 :: Word) 1
 
=={{header|HicEst}}==
There is no rotate and no shift support built in to HicEst
<langsyntaxhighlight lang="hicest">i = IAND(k, j)
i = IOR( k, j)
i = IEOR(k, j)
i = NOT( k )</langsyntaxhighlight>
 
=={{header|HPPPL}}==
<langsyntaxhighlight lang="hpppl">EXPORT BITOPS(a, b)
BEGIN
PRINT(BITAND(a, b));
Line 3,419 ⟶ 3,769:
PRINT(BITSR(a, b));
// HPPPL has no builtin rotates or arithmetic right shift.
END;</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
bitdemo(255,2)
bitdemo(-15,3)
Line 3,442 ⟶ 3,791:
procedure demowrite(vs,v)
return write(vs, ": ", v, " = ", int2bit(v),"b")
end</langsyntaxhighlight>
 
Icon/Unicon implements bitwise operations on integers. Because integers can be transparently large integers operations that require fixed sizes don't make sense and aren't defined. These include rotation and logical shifting (shift is arithmetic) . Please note also that 'not' is a reserved word and the negation function is 'icom'
Line 3,466 ⟶ 3,815:
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.
 
<langsyntaxhighlight Informlang="inform 6">[ bitwise a b temp;
print "a and b: ", a & b, "^";
print "a or b: ", a | b, "^";
Line 3,485 ⟶ 3,833:
print "a >> b (logical): ", temp, "^";
];
</syntaxhighlight>
</lang>
 
=={{header|J}}==
 
Here are the "[http://www.jsoftware.com/help/dictionary/dbdotn.htm bitwise operators]":
 
<langsyntaxhighlight 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,499 ⟶ 3,846:
bRAshift=: 34 b.~ -
bLrot=: 32 b.~
bRrot=: 32 b.~ -</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="j">bitwise=: 1 :0
:
smoutput (((":x),"1' ',.(>u),.' '),"1":y),"1' => ',"1'.X'{~#:x u`:0 y
)</langsyntaxhighlight>
 
And here they are in action:
 
<langsyntaxhighlight lang="j"> 254 bAND`bOR`bXOR`b1NOT`bLshift`bRshift`bRAshift`bLrot`bRrot bitwise 3
254 bAND 3 => ............................X.
254 bOR 3 => ......................XXXXXXXX
Line 3,519 ⟶ 3,866:
254 bRAshift 3 => .........................XXXXX
254 bLrot 3 => ...................XXXXXXX....
254 bRrot 3 => .........................XXXXX</langsyntaxhighlight>
 
Further test
<syntaxhighlight lang="j">
<lang j>
bXOR/ 3333 5555 7777 9999
8664
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<langsyntaxhighlight 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,538 ⟶ 3,884:
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+
}</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="java">a <<= 3;
a = a << 3;
a *= 8; //2 * 2 * 2 = 8
a = a * 8;</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="javascript">function bitwise(a, b){
alert("a AND b: " + (a & b));
alert("a OR b: "+ (a | b));
Line 3,556 ⟶ 3,901:
alert("a >> b: " + (a >> b)); // arithmetic right shift
alert("a >>> b: " + (a >>> b)); // logical right shift
}</langsyntaxhighlight>
=={{header|jq}}==
'''Works with jq, the C implementation of jq'''
 
'''Works with gojq, the Go implementation of jq'''
 
jq has no built-in bitwise operations, but the
[[:Category:Jq/bitwise.jq | "bitwise" module]]
defines
all those needed for the task at hand except for rotations.
Here `rotateLeft` and rotateRight` functions are defined relative to a given width.
 
The examples are taken from the entry for [[#Wren|Wren]].
<syntaxhighlight lang="jq">
include "bitwise" {search: "."}; # adjust as required
 
def leftshift($n; $width):
[(range(0,$n)| 0), limit($width - $n; bitwise)][:$width] | to_int;
 
# Using a width of $width bits: x << n | x >> ($width-n)
def rotateLeft($x; $n; $width):
$x | bitwise_or(leftshift($n; $width); rightshift($width-$n));
 
# Using a width of $width bits: x << n | x >> ($width-n)
def rotateRight($x; $n; $width):
$x | bitwise_or(rightshift($n); leftshift($width-$n; $width) );
 
def task($x; $y):
def isInteger: type == "number" and . == round;
if ($x|isInteger|not) or ($y|isInteger|not) or
$x < 0 or $y < 0 or $x > 4294967295 or $y > 4294967295
then "Operands must be in the range of a 32-bit unsigned integer" | error
else
" x = \($x)",
" y = \($y)",
" x & y = \(bitwise_and($x; $y))",
" x | y = \(bitwise_or($x; $y))",
" x ^ y = \(null | xor(x; $y))",
"~x = \(32 | flip($x))",
" x << y = \($x | leftshift($y))",
" x >> y = \($x | rightshift($y))",
" x rl y = \(rotateLeft($x; $y; 32))",
" x rr y = \(rotateRight($x; $y; 32))"
end;
 
task(10; 2)
</syntaxhighlight>
{{output}}
<pre>
x = 10
y = 2
x & y = 2
x | y = 10
x ^ y = 8
~x = 4294967295
x << y = 40
x >> y = 2
x rl y = 40
x rr y = 2147483650
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># Version 5.2
@show 1 & 2 # AND
@show 1 | 2 # OR
Line 3,571 ⟶ 3,975:
@show A ror(A,1) ror(A,2) ror(A,5) # ROTATION RIGHT
@show rol(A,1) rol(A,2) rol(A,5) # ROTATION LEFT
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,592 ⟶ 3,996:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
<lang scala>/* for symmetry with Kotlin's other binary bitwise operators
fun main() {
we wrap Java's 'rotate' methods as infix functions */
// inferred type of x and y is Int (32-bit signed integer)
infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance)
infix fun Int.ror(distance: Int): Int = Integer.rotateRight(this, distance)
 
fun main(args: Array<String>) {
// inferred type of x and y is Int i.e. 32 bit signed integers
val x = 10
val y = 2
println("x = $x")
println("y = $y")
println("NOT x = ${x.inv()}")
println("x AND y = ${x and y}")
println("x OR y = ${x or y}")
println("x XOR y = ${x xor y}")
 
// All operations below actually return (x OP (y % 32)) so that a value is never completely shifted out
println("x SHL y = ${x shl y}")
println("x ASR y = ${x shr y}") // arithmetic shift right (sign bit filled)
println("x LSR y = ${x ushr y}") // logical shift right (zero filled)
println("x ROL y = ${x rol .rotateLeft(y)}")
println("x ROR y = ${x ror .rotateRight(y)}")
}</langsyntaxhighlight>
 
{{out}}
<pre>
x = 10
y = 2
NOT x = -11
x AND y = 2
x OR y = 10
x XOR y = 8
x SHL y = 40
Line 3,632 ⟶ 4,034:
 
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate.
<langsyntaxhighlight lang="lisp">(defun bitwise (a b)
(lists:map
(lambda (x) (io:format "~p~n" `(,x)))
Line 3,658 ⟶ 4,060:
(describe "bsl" a b (bsl a b))
(describe "bsr" a b (bsr a b))))
</syntaxhighlight>
</lang>
 
Example usage:
<langsyntaxhighlight lang="lisp">
> (bitwise 255 170)
170
Line 3,679 ⟶ 4,081:
ok
>
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
Written as functions.
<syntaxhighlight lang="lb">
<lang lb>
' bitwise operations on byte-sized variables
 
Line 3,730 ⟶ 4,131:
dec2Bin$ =right$( "00000000" +dec2Bin$, 8)
end function
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
Lingo has built-in functions for bitwise AND, OR, XOR and NOT:
<langsyntaxhighlight lang="lingo">put bitAND(2,7)
put bitOR(2,7)
put bitXOR(2,7)
put bitNOT(7)</langsyntaxhighlight>
Bit shifting and rotating has to be implemented by custom functions.
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="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,748 ⟶ 4,147:
 
-- Ouput
and: 2, or: 255, xor: 253, not: 4294967040</langsyntaxhighlight>
LiveCode does not provide built-in bit-shift operations.
 
=={{header|LLVM}}==
<langsyntaxhighlight lang="llvm">; ModuleID = 'test.o'
;e means little endian
;p: { pointer size : pointer abi : preferred alignment for pointers }
Line 3,811 ⟶ 4,209:
 
;Declare external fuctions
declare i32 @printf(i8* nocapture, ...) nounwind</langsyntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">to bitwise :a :b
(print [a and b:] BitAnd :a :b)
(print [a or b:] BitOr :a :b)
Line 3,825 ⟶ 4,222:
(print [-a ashift -b:] AShift minus :a minus :b)
end
bitwise 255 5</langsyntaxhighlight>
The output of this program is:
<langsyntaxhighlight lang="logo">a and b: 5
a or b: 255
a xor b: 250
Line 3,833 ⟶ 4,230:
a lshift b: 8160
a lshift -b: 7
-a ashift -b: -8</langsyntaxhighlight>
 
=={{header|LSE64}}==
{{incorrect|LSE64|No reason given.}}
<langsyntaxhighlight lang="lse64">over : 2 pick
2dup : over over
Line 3,847 ⟶ 4,243:
" not A=" ,t ~ ,h nl
\ a \ 7 bitwise # hex literals</langsyntaxhighlight>
 
=={{header|Lua}}==
 
LuaBitOp implements bitwise functionality for Lua:
 
<langsyntaxhighlight lang="lua">local bit = require"bit"
 
local vb = {
Line 3,918 ⟶ 4,313:
assert(bit.bxor(1,2) == 3)
assert(bit.bor(1,2,4,8,16,32,64,128) == 255)
</syntaxhighlight>
</lang>
 
The ''RiscLua'' dialect, for [http://lua.riscos.org.uk/ '''RISC OS'''], has
Line 3,926 ⟶ 4,321:
==={{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:
<langsyntaxhighlight lang="lua">a = 0xAA55AA55
b = 0x4
print(string.format("%8X and %8X = %16X", a, b, a&b))
Line 3,940 ⟶ 4,335:
print(string.format("%8X sar %8X = %16X", a, b, sar(a,b)))
print(string.format("%8X rol %8X = %16X", a, b, rol(a,b)))
print(string.format("%8X ror %8X = %16X", a, b, ror(a,b)))</langsyntaxhighlight>
{{out}}
<pre>AA55AA55 and 4 = 4
Line 3,951 ⟶ 4,346:
AA55AA55 rol 4 = A55AA55A
AA55AA55 ror 4 = 5AA55AA5</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
with(Bits):
bit:=proc(A,B)
Line 3,972 ⟶ 4,366:
return a,b,c,d,e,f,g,i;
end proc;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
Most functions are built-in or can be made really easily:
<langsyntaxhighlight Mathematicalang="mathematica">(*and xor and or*)
BitAnd[integer1, integer2]
BitXor[integer1, integer2]
Line 3,993 ⟶ 4,386:
 
(*right arithmetic shift*)
FromDigits[Prepend[Most[#], #[[1]]], 2] &[IntegerDigits[integer1, 2]]</langsyntaxhighlight>
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:
<langsyntaxhighlight Mathematicalang="mathematica">BitXor[3333, 5555, 7777, 9999]</langsyntaxhighlight>
gives back:
<syntaxhighlight lang Mathematica="mathematica">8664</langsyntaxhighlight>
 
=={{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]
 
<langsyntaxhighlight MATLABlang="matlab">function bitwiseOps(a,b)
 
disp(sprintf('%d and %d = %d', [a b bitand(a,b)]));
Line 4,010 ⟶ 4,402:
disp(sprintf('%d >> %d = %d', [a b bitshift(a,-b)]));
 
end</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight MATLABlang="matlab">>> bitwiseOps(255,2)
255 and 2 = 2
255 or 2 = 255
255 xor 2 = 253
255 << 2 = 1020
255 >> 2 = 63</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">load(functs)$
 
a: 3661$
Line 4,043 ⟶ 4,434:
 
logand(a, -a - 1);
/* 0 */</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn bitwise a b =
(
format "a and b: %\n" (bit.and a b)
Line 4,056 ⟶ 4,446:
)
 
bitwise 255 170</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight MLlang="ml/Ii">MCSKIP "WITH" NL
"" Bitwise operations
"" assumes macros on input stream 1, terminal on stream 2
Line 4,078 ⟶ 4,467:
MCSET S1=1
*MCSET S10=2
</syntaxhighlight>
</lang>
 
=={{header|Modula-3}}==
 
<langsyntaxhighlight lang="modula3">MODULE Bitwise EXPORTS Main;
 
IMPORT IO, Fmt, Word;
Line 4,103 ⟶ 4,491:
BEGIN
Bitwise(255, 5);
END Bitwise.</langsyntaxhighlight>
 
Output:
Line 4,116 ⟶ 4,504:
c RightRotate b: f8000007
</pre>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
<doc>
<h2>bitwise operations</h2>
Line 4,174 ⟶ 4,561:
if b == null b = 0;
 
bitwise(a,b);</langsyntaxhighlight>
 
{{out}}
Line 4,200 ⟶ 4,587:
a ROL b: is not directly supported in Neko syntax
a ROR b: is not directly supported in Neko syntax</pre>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">def i = 255;
def j = 2;
 
Line 4,214 ⟶ 4,600:
WriteLine($"$(i :> uint) rshift $j is $(c >> j)"); // 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 Nemerle, but you could define your own w/ a macro if you really wanted it</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc bitwise(a, b) =
echo "a and b: " , a and b
echo "a or b: ", a or b
Line 4,223 ⟶ 4,608:
echo "not a: ", not a
echo "a << b: ", a shl b
echo "a >> b: ", a shr b</langsyntaxhighlight>
 
=={{header|NSIS}}==
All bitwise operations in NSIS are handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 IntOp] instruction.
<langsyntaxhighlight lang="nsis">Function Bitwise
Push $0
Push $1
Line 4,253 ⟶ 4,637:
Pop $1
Pop $0
FunctionEnd</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<langsyntaxhighlight lang="oberon2">
MODULE Bitwise;
IMPORT
Line 4,284 ⟶ 4,667:
Do(10,2);
END Bitwise.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,299 ⟶ 4,682:
a arithmetic right shift b :> 2
</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
 
bundle Default {
Line 4,317 ⟶ 4,699:
}
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight 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,328 ⟶ 4,709:
Printf.printf "a asr b: %d\n" (a asr b); (* arithmetic right shift *)
Printf.printf "a lsr b: %d\n" (a lsr b); (* logical right shift *)
;;</langsyntaxhighlight>
 
=={{header|Octave}}==
 
There's no arithmetic shift nor rotation (and the not can be done through a xor)
 
<langsyntaxhighlight 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,344 ⟶ 4,724:
endfunction
 
bitops(0x1e, 0x3);</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
There is no built-in for not and rotation
 
<langsyntaxhighlight Oforthlang="oforth">: bitwise(a, b)
a b bitAnd println
a b bitOr println
a b bitXor println
a bitLeft(b) println
a bitRight(b) println ;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">/* ooRexx *************************************************************
/ Bit Operations work as in Rexx (of course)
* Bit operations are performed up to the length of the shorter string.
Line 4,377 ⟶ 4,755:
Say 'a~bitor(b,p):'c2b(a~bitor(b,p)) c2x(a~bitor(b,p))
Exit
c2b: return x2b(c2x(arg(1)))</langsyntaxhighlight>
Output:
<pre>
Line 4,388 ⟶ 4,766:
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>.
<langsyntaxhighlight lang="parigp">bo(a,b)={
print("And: "bitand(a,b));
print("Or: "bitor(a,b));
Line 4,402 ⟶ 4,778:
print("Left shift: ",a<<b);
print("Right shift: ",a>>b);
}</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="pascal">var
a, b: integer;
begin
Line 4,414 ⟶ 4,789:
writeln('a or b = ', a or b); { 14 = 1110 }
writeln('a xor b = ', a xor b) { 6 = 0110 }
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use integer;
sub bitwise :prototype($$) {
($a, $b) = @_;
print 'a and b: '. ($a & $b) ."\n";
Line 4,431 ⟶ 4,805:
print 'a << b: ', $a << $b, "\n"; # left shift
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift
}</langsyntaxhighlight>
 
=={{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.
Phix has four builtin bitwise operations (and/or/xor/not), all of which have sequence variants. There are no builtin shift or rotate operations,
<!--<syntaxhighlight lang="phix">(phixonline)-->
but it would be easy to devise one using / or * powers of 2 [which the compiler often optimises to single machine instructions] and the builtins,
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Bitwise_operations.exw</span>
see [[Bitwise_operations#C|C]] for an example, or use inline assembly as shown below.
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<!--<lang Phix>-->
<span style="color: #008080;">enum</span> <span style="color: #000000;">SHL</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">SAR</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">SHR</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ROL</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ROR</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">bitop</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SHL</span> <span style="color: #008080;">then</span>
#ilASM{
<span style="color: #000080;font-style:italic;">-- Note: Phix doesn't quietly discard high bits...</span>
[32]
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">and_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span> <span style="color: #0000FF;"><<</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#FFFF_FFFF</span><span style="color: #0000FF;">)</span>
mov eax,[a]
<span style="color: #008080;">elsif</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SAR</span> <span style="color: #008080;">then</span>
call :%pLoadMint
<span style="color: #000080;font-style:italic;">-- Note: Phix doesn't really do "unsigned numbers",
mov ecx,[b]
-- mov edx,[op] Should you want to treat 4G-1 as -1 then:</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">></span><span style="color: #000000;">#7FFF_FFFF</span> <span style="color: #008080;">then</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">#1_0000_0000</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
cmp dl,SHL
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">and_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span> <span style="color: #0000FF;">>></span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#FFFF_FFFF</span><span style="color: #0000FF;">)</span>
jne @f
<span style="color: #008080;">elsif</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #000000;">SHR</span> <span style="color: #008080;">then</span>
shl eax,cl
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">and_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span> <span style="color: #0000FF;">>></span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#FFFF_FFFF</span><span style="color: #0000FF;">)</span>
jmp :storeres
<span style="color: #008080;">elsif</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #000000;">ROL</span> <span style="color: #008080;">then</span>
@@:
<span style="color: #008080;">return</span> <span style="color: #7060A8;">or_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span> <span style="color: #0000FF;">>></span> <span style="color: #000000;">32</span><span style="color: #0000FF;">-</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span> <span style="color: #0000FF;"><<</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#FFFF_FFFF</span><span style="color: #0000FF;">))</span>
cmp dl,SAR
<span style="color: #008080;">elsif</span> <span style="color: #000000;">op</span><span style="color: #0000FF;">=</span><span style="color: #000000;">ROR</span> <span style="color: #008080;">then</span>
jne @f
<span style="color: #008080;">return</span> <span style="color: #7060A8;">or_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span> <span style="color: #0000FF;">>></span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span> <span style="color: #0000FF;"><<</span> <span style="color: #000000;">32</span><span style="color: #0000FF;">-</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#FFFF_FFFF</span><span style="color: #0000FF;">))</span>
sar eax,cl
<span style="color: #008080;">else</span>
jmp :storeres
<span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span>
@@:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
cmp dl,SHR
jne @f
shr eax,cl
jmp :storeres
@@:
cmp dl,ROL
jne @f
rol eax,cl
jmp :storeres
@@:
cmp dl,ROR
jne @f
ror eax,cl
jmp :storeres
@@:
int3
::storeres
lea edi,[res]
call :%pStoreMint
[64]
mov rax,[a]
mov rcx,[b]
mov edx,[op]
cmp dl,SHL
jne @f
shl rax,cl
jmp :storeres
@@:
cmp dl,SAR
jne @f
sar rax,cl
jmp :storeres
@@:
cmp dl,SHR
jne @f
shr rax,cl
jmp :storeres
@@:
cmp dl,ROL
jne @f
rol rax,cl
jmp :storeres
@@:
cmp dl,ROR
jne @f
ror eax,cl
jmp :storeres
@@:
int3
::storeres
lea rdi,[res]
call :%pStoreMint
}
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">bitwise</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"and_bits(%b,%b) = %032b\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #0000007060A8;">and_bitsand_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" or_bits(%b,%b) = %032b\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #0000007060A8;">or_bitsor_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"xor_bits(%b,%b) = %032b\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #0000007060A8;">xor_bitsxor_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"not_bits(%b) = %032b\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #0000007060A8;">not_bitsnot_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" shl(%b,%b) = %032b\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bitop</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SHL</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" sar(%b,%b) = %032b\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bitop</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SAR</span><span style="color: #0000FF;">)})</span>
Line 4,526 ⟶ 4,848:
<span style="color: #000000;">bitwise</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0x800000FE</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,539 ⟶ 4,861:
ror(10000000000000000000000011111110,111) = 11111101000000000000000000000001
</pre>
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">6 var a 3 var b
 
def tab
Line 4,557 ⟶ 4,878:
"OR = " print tab a b bitor printBits
"XOR = " print tab a b bitxor printBits
"NOT = " print tab a bitnot printBits</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function bitwise($a, $b)
{
function zerofill($a,$b) {
Line 4,574 ⟶ 4,894:
echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
PicoLisp has no specific word size. Numbers grow to arbitrary length. Therefore,
Line 4,582 ⟶ 4,901:
 
Bitwise AND:
<langsyntaxhighlight PicoLisplang="picolisp">: (& 6 3)
-> 2
 
: (& 7 3 1)
-> 1</langsyntaxhighlight>
Bitwise AND-Test (tests if all bits in the first argument are set in the
following arguments):
<langsyntaxhighlight PicoLisplang="picolisp">: (bit? 1 2)
-> NIL
 
Line 4,596 ⟶ 4,915:
 
: (bit? 6 15 255)
-> 6</langsyntaxhighlight>
Bitwise OR:
<langsyntaxhighlight PicoLisplang="picolisp">: (| 1 2)
-> 3
 
: (| 1 2 4 8)
-> 15</langsyntaxhighlight>
Bitwise XOR:
<langsyntaxhighlight PicoLisplang="picolisp">: (x| 2 7)
-> 5
 
: (x| 2 7 1)
-> 4</langsyntaxhighlight>
Shift (right with a positive count, left with a negative count):
<langsyntaxhighlight PicoLisplang="picolisp">: (>> 1 8)
-> 4
 
Line 4,620 ⟶ 4,939:
 
: (>> -1 -16)
-> -32</langsyntaxhighlight>
 
=={{header|Pike}}==
Rotate operations are not available
<syntaxhighlight lang="pike">
<lang Pike>
void bitwise(int a, int b)
{
Line 4,643 ⟶ 4,961:
bitwise(255, 30);
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 4,654 ⟶ 4,972:
a << b & 0xffffffff (32bit cap): 0xc0000000
</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* PL/I can perform bit operations on binary integers. */
k = iand(i,j);
k = ior(i,j);
Line 4,681 ⟶ 4,998:
u = substr(s, length(s), 1) || substr(s, 1, length(s)-1); /* implements rotate right. */
u = substr(s, 2) || substr(s, 1, 1); /* implements rotate left. */
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
 
<langsyntaxhighlight lang="pop11">define bitwise(a, b);
printf(a && b, 'a and b = %p\n');
printf(a || b, 'a or b = %p\n');
Line 4,692 ⟶ 5,008:
printf(a << b, 'left shift of a by b = %p\n');
printf(a >> b, 'arithmetic right shift of a by b = %p\n');
enddefine;</langsyntaxhighlight>
 
Conceptually in Pop11 integers have infinite precision, in particular negative numbers conceptually have infinitely many leading 1's in two's complement notation. Hence, logical right shift is not defined. If needed, logical right shift can be simulated by masking high order bits.
 
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}}
<langsyntaxhighlight PowerShelllang="powershell">$X -band $Y
$X -bor $Y
$X -bxor $Y
-bnot $X</langsyntaxhighlight>
{{works with|PowerShell|3.0}}
<langsyntaxhighlight PowerShelllang="powershell">$X -shl $Y
# Arithmetic right shift
$X -shr $Y
 
# 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))</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Bitwise(a, b)
Debug a & b ; And
Debug a | b ;Or
Line 4,743 ⟶ 5,057:
!mov dword [p.v_Temp], edx
Debug Temp
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
===Python 3===
Line 4,753 ⟶ 5,066:
binary output formatting in calculations and result displays.
 
<langsyntaxhighlight lang="python">def bitwise_built_ins(width, a, b):
mask = (1 << width) - 1
print(f"""\
Line 4,861 ⟶ 5,174:
if __name__ == '__main__':
bitwise_built_ins(8, 27, 125)
helper_funcs(8, 27)</langsyntaxhighlight>
 
{{out}}
Line 4,919 ⟶ 5,232:
 
===Python 2===
<langsyntaxhighlight lang="python">def bitwise(a, b):
print 'a and b:', a & b
print 'a or b:', a | b
Line 4,925 ⟶ 5,238:
print 'not a:', ~a
print 'a << b:', a << b # left shift
print 'a >> b:', a >> b # arithmetic right shift</langsyntaxhighlight>
 
Python does not have built in rotate or logical right shift operations.
Line 4,931 ⟶ 5,244:
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:
 
<langsyntaxhighlight lang="python"># 8-bit bounded shift:
x = x << n & 0xff
# ditto for 16 bit:
Line 4,938 ⟶ 5,251:
x = x << n & 0xffffffff
# ... and 64-bit:
x = x << n & 0xffffffffffffffff</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight 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 4,982 ⟶ 5,295:
return n
n &= mask(width)
return (n >> rotations) | ((n << (width - rotations)) & mask(width))</langsyntaxhighlight>
 
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">
' no rotations and shift aritmetic are available in QB64
' Bitwise operator in Qbasic and QB64
'AND (operator) the bit is set when both bits are set.
'EQV (operator) the bit is set when both are set or both are not set.
'IMP (operator) the bit is set when both are set or both are unset or the second condition bit is set.
'OR (operator) the bit is set when either bit is set.
'NOT (operator) the bit is set when a bit is not set and not set when a bit is set.
'XOR (operator) the bit is set when just one of the bits are set.
Print "Qbasic and QB64 operators"
Print " Operator 1 vs 1 1 vs 0 0 vs 0"
 
Print "AND", 1 And 1, 1 And 0, 0 And 0
Print " OR", 1 Or 1, 1 Or 0, 0 Or 0
Print "XOR", 1 Xor 1, 1 Xor 0, 0 Xor 0
Print "EQV", 1 Eqv 1, 1 Eqv 0, 0 Eqv 0
Print "IMP", 1 Imp 1, 1 Imp 0, 0 Imp 0
Print "NOT", Not 1, Not 0, Not -1, Not -2
 
Print "QB64 operators"
Dim As _Byte a, b, c
a = 1: b = 1: c = 1
For i = 1 To 4
Print a, b, c
Print _SHL(a, i), _SHL(b, i * 2), _SHL(c, i * 3)
Next
a = 16: b = 32: c = 8
For i = 1 To 4
Print a, b, c
Print _SHR(a, i), _SHR(b, i * 2), _SHR(c, i * 3)
Next
 
</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>.
 
<langsyntaxhighlight Quackerylang="quackery"> [ [] swap
64 times
[ 2 /mod
Line 5,010 ⟶ 5,356:
say "bitwise RROTATE: " rrot64 echobin ] is task ( n n --> )
 
hex FFFFF hex F task</langsyntaxhighlight>
 
{{out}}
Line 5,025 ⟶ 5,371:
bitwise RROTATE: 1111111111111110000000000000000000000000000000000000000000011111
</pre>
 
=={{header|R}}==
 
=== Native functions in R 3.x ===
<langsyntaxhighlight rlang="rsplus"># Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd
 
a <- 35
Line 5,038 ⟶ 5,383:
bitwNot(a)
bitwShiftL(a, 2)
bitwShiftR(a, 2)</syntaxhighlight>
 
# See also httphttps://cran.r-project.org/srcdoc/basemanuals/r-release/NEWS.3.html</lang>.
 
===Using ''as.hexmode'' or ''as.octmode''===
<langsyntaxhighlight rlang="rsplus">a <- as.hexmode(35)
b <- as.hexmode(42)
as.integer(a & b) # 34
as.integer(a | b) # 43
as.integer(xor(a, b)) # 9</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight Rlang="rsplus">intToLogicalBits <- function(intx) as.logical(intToBits(intx))
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb]))
"%AND%" <- function(x, y)
Line 5,063 ⟶ 5,408:
 
35 %AND% 42 # 34
35 %OR% 42 # 42</langsyntaxhighlight>
 
===Using ''bitops'' package===
<langsyntaxhighlight Rlang="rsplus">library(bitops)
bitAnd(35, 42) # 34
bitOr(35, 42) # 43
Line 5,073 ⟶ 5,418:
bitShiftL(35, 1) # 70
bitShiftR(35, 1) # 17
# Note that no bit rotation is provided in this package</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define a 255)
Line 5,086 ⟶ 5,430:
(arithmetic-shift a b) ; left shift
(arithmetic-shift a (- b))) ; right shift
</syntaxhighlight>
</lang>
Output:
<pre>
'(5 255 250 -256 8160 7)
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2017.05}}
<syntaxhighlight lang="raku" perl6line>constant MAXINT = uint.Range.max;
constant BITS = MAXINT.base(2).chars;
 
Line 5,122 ⟶ 5,465:
sub say_bit ($message, $value) {
printf("%30s: %{'0' ~ BITS}b\n", $message, $value +& MAXINT);
}</langsyntaxhighlight>
{{out}}
<pre> 7: 0000000000000000000000000000000000000000000000000000000000000111
Line 5,147 ⟶ 5,490:
-65432 shift left 31: 1111111111111111100000000011010000000000000000000000000000000000
-65432 rotate left 31: 1111111111111111100000000011010001111111111111111111111111111111</pre>
 
=={{header|Red}}==
<langsyntaxhighlight lang="red">Red [Source: https://github.com/vazub/rosetta-red]
 
a: 10
Line 5,166 ⟶ 5,508:
; there are no circular shift operators in Red
]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,179 ⟶ 5,521:
a << b: 40
</pre>
 
=={{header|Retro}}==
There is no predefined arithmetic shifts in Retro.
 
<syntaxhighlight lang="retro">
<lang Retro>
: bitwise ( ab- )
cr
Line 5,194 ⟶ 5,535:
2over << "a << b = %d\n" puts
2over >> "a >> b = %d\n" puts
2drop ;</langsyntaxhighlight>
 
=={{header|REXX}}==
<pre>
Line 5,207 ⟶ 5,547:
╚═══════════════════════════════════════════════════════════════════════════════════════╝
</pre>
<langsyntaxhighlight 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,229 ⟶ 5,569:
bOr: return c2d( bitor( d2c( arg(1) ), d2c( arg(2) ) ) )
bXor: return c2d( bitxor( d2c( arg(1) ), d2c( arg(2) ) ) )
bShiftR: $=substr(reverse(d2b(arg(1))),arg(2)+1); if $='' then $=0; return b2d(reverse($))</langsyntaxhighlight>
{{out|output}}
<pre>
Line 5,243 ⟶ 5,583:
2 A [»B] 10
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
x = 8
y = 2
Line 5,255 ⟶ 5,594:
see "x << y - Binary Left Shift : " + (x << y) + nl
see "x >> y - Binary Right Shift : " + (x >> y) + nl
</syntaxhighlight>
</lang>
 
=={{header|RLaB}}==
 
Line 5,262 ⟶ 5,600:
are integers then the result of the operation is an integer as well.
 
<langsyntaxhighlight RLaBlang="rlab">>> x = int(3);
>> y = int(1);
>> z = x && y; printf("0x%08x\n",z); // logical 'and'
Line 5,274 ⟶ 5,612:
0x00000006
>> z = x / i2; printf("0x%08x\n",z); // right-shift is division by 2 where both arguments are integers
0x00000001</langsyntaxhighlight>
 
=={{header|Robotic}}==
<langsyntaxhighlight lang="robotic">
input string "First value"
set "local1" to "input"
Line 5,293 ⟶ 5,630:
end
. "Bitwise rotation is not natively supported"
</syntaxhighlight>
</lang>
=={{header|RPL}}==
≪ { AND OR XOR NOT SL SR ASR RL RR } → a b ops
≪ {} 1 ops SIZE '''FOR''' j
a →STR " " + '''IF''' j 3 ≤ '''THEN''' b →STR + " " + '''END'''
ops j GET →STR 2 OVER SIZE 1 - SUB + " -> " +
a j 3 ≤ b IFT ops j GET EVAL →STR + +
'''NEXT'''
≫ ≫ ‘'''BITOPS'''’ STO
{{out}}
<pre>
{ "# 355h # 113h AND -> # 111h"
"# 355h # 113h OR -> # 357h"
"# 355h # 113h XOR -> # 246h"
"# 355h NOT -> # FCAAh"
"# 355h SL -> # 6AAh"
"# 355h SR -> # 1AAh"
"# 355h ASR -> # 1AAh"
"# 355h RL -> # 6AAh"
"# 355h RR -> # 81AAh" }
</pre>
Operations made with a word size set at 16 bits.
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def bitwise(a, b)
form = "%1$7s:%2$6d %2$016b"
puts form % ["a", a]
Line 5,308 ⟶ 5,666:
end
 
bitwise(14,3)</langsyntaxhighlight>
 
{{out}}
Line 5,323 ⟶ 5,681:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
let a: u8 = 105;
let b: u8 = 91;
Line 5,334 ⟶ 5,692:
println!("a << 3 = {:0>8b}", a << 3);
println!("a >> 3 = {:0>8b}", a >> 3);
}</langsyntaxhighlight>
 
Output:
Line 5,348 ⟶ 5,706:
a >> 3 = 00001101
</pre>
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">/* rotations are not available, but are easy to implement with the other bitwise operators */
data _null_;
a=105;
Line 5,361 ⟶ 5,718:
h=brshift(a,1);
put _all_;
run;</langsyntaxhighlight>
 
=={{header|S-BASIC}}==
S-BASIC does not have bitwise shift or rotate operators. The test values are taken from the 11l example.
<syntaxhighlight lang="BASIC">
var a, b = integer
a = 10
b = 2
print "a ="; a; tab(16); hex$(a)
print "b ="; b; tab(16); hex$(b)
print "a and b ="; a and b; tab(16); hex$(a and b)
print "a or b ="; a or b; tab(16); hex$(a or b)
print "a xor b ="; a xor b; tab(16); hex$(a xor b)
print "not a ="; not a; tab(16); hex$(not a)
 
end
</syntaxhighlight>
{{out}}
<pre>
a = 10 000A
b = 2 0002
a and b = 2 0002
a or b = 10 000A
a xor b = 688 02CD
not a =-11 FFF5
</pre>
 
=={{header|Scala}}==
 
<langsyntaxhighlight lang="scala">def bitwise(a: Int, b: Int) {
println("a and b: " + (a & b))
println("a or b: " + (a | b))
Line 5,375 ⟶ 5,757:
println("a rot b: " + Integer.rotateLeft(a, b)) // Rotate Left
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^6</math>RS}}
<langsyntaxhighlight lang="scheme">(import (rnrs arithmetic bitwise (6)))
 
(define (bitwise a b)
Line 5,393 ⟶ 5,775:
(newline))
 
(bitwise 255 5)</langsyntaxhighlight>
Output:
<syntaxhighlight lang="text">5
255
250
-256
7</langsyntaxhighlight>
 
''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,411 ⟶ 5,792:
Right shifting of bin32 values is done with logical shifts.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bin32.s7i";
 
Line 5,440 ⟶ 5,821:
bitwise(65076, 6);
bitwise(bin32(65076), bin32(6));
end func;</langsyntaxhighlight>
 
{{out}}
Line 5,459 ⟶ 5,840:
a rolR b: 11010000000000000000001111111000
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func bitwise(a, b) {
say ('a and b : ', a & b)
say ('a or b : ', a | b)
Line 5,470 ⟶ 5,850:
}
bitwise(14,3)</langsyntaxhighlight>
{{out}}
<pre>
Line 5,480 ⟶ 5,860:
a >> b : 1
</pre>
 
=={{header|Simula}}==
<langsyntaxhighlight 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,584 ⟶ 5,963:
END;
END
</syntaxhighlight>
</lang>
{{out}}
<pre>A AND B : 2
Line 5,595 ⟶ 5,974:
A ROTR B : -1073741823
</pre>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">[ |:a :b |
 
inform: (a bitAnd: b) printString.
Line 5,606 ⟶ 5,984:
inform: (a >> b) printString.
 
] applyTo: {8. 12}.</langsyntaxhighlight>
'''Bold text'''
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
Line 5,614 ⟶ 5,991:
{{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.
<langsyntaxhighlight lang="smalltalk">| testBitFunc |
testBitFunc := [ :a :b |
('%1 and %2 is %3' % { a. b. (a bitAnd: b) }) displayNl.
Line 5,623 ⟶ 6,000:
('%1 right shift %2 is %3' % { a. b. (a bitShift: (b negated)) }) displayNl.
].
testBitFunc value: 16r7F value: 4 .</langsyntaxhighlight>
 
in addition to the above,
{{works with|Smalltalk/X}}
<langsyntaxhighlight 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,634 ⟶ 6,011:
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"</langsyntaxhighlight>
 
Notice that all of those work on arbitrarily large integers (i.e. 1000 factorial lowBit -> 995).
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "bitarith" )
@( description, "Write a routine to perform a bitwise AND, OR, and XOR on" )
@( description, "two integers, a bitwise NOT on the first integer, a left" )
@( description, "shift, right shift, right arithmetic shift, left rotate," )
@( description, "and right rotate. All shifts and rotates should be done on" )
@( description, "the first integer with a shift/rotate amount of the second" )
@( description, "integer." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Bitwise_operations" );
pragma license( unrestricted );
 
pragma software_model( shell_script );
pragma restriction( no_external_commands );
 
procedure bitarith is
A : constant natural := 255;
B : constant natural := 170;
X : constant natural := 128;
N : constant natural := 1;
begin
put( "A and B = " ) @ (A and B); new_line;
put( "A or B = " ) @ (A or B); new_line;
put( "A xor B = " ) @ (A xor B); new_line;
new_line;
put( "A << B = " ) @ ( numerics.shift_left( X, N ) ); new_line;
put( "A >> B = " ) @ ( numerics.shift_right( X, N ) ); new_line;
put( "A >>> B = " ) @ ( numerics.shift_right_arithmetic( X, N ) ); new_line;
put( "A rotl B = " ) @ ( numerics.rotate_left( X, N ) ); new_line;
put( "A rotr B = " ) @ ( numerics.rotate_right( X, N ) ); new_line;
end bitarith;</syntaxhighlight>
 
=={{header|Standard ML}}==
For integers, IntInfs provide bitwise operations:
<langsyntaxhighlight 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,647 ⟶ 6,059:
print ("a lsl b: " ^ IntInf.toString (IntInf.<< (IntInf.fromInt a, Word.fromInt b )) ^ "\n"); (* left shift *)
print ("a asr b: " ^ IntInf.toString (IntInf.~>> (IntInf.fromInt a, Word.fromInt b )) ^ "\n") (* arithmetic right shift *)
)</langsyntaxhighlight>
More shifts are available for words (unsigned ints):
<langsyntaxhighlight 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,657 ⟶ 6,069:
print ("a asr b: " ^ Word.fmt StringCvt.DEC (Word.~>> (a, b) ) ^ "\n"); (* arithmetic right shift *)
print ("a asr b: " ^ Word.fmt StringCvt.DEC (Word.>> (a, b) ) ^ "\n") (* logical right shift *)
)</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="swift">func bitwise(a: Int, b: Int) {
// All bitwise operations (including shifts)
// require both operands to be the same type
Line 5,677 ⟶ 6,088:
}
 
bitwise(-15,3)</langsyntaxhighlight>
{{out}}
<pre>
Line 5,688 ⟶ 6,099:
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:
<langsyntaxhighlight SystemVeriloglang="systemverilog">program main;
 
initial begin
Line 5,710 ⟶ 6,120:
end
 
endprogram</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight SystemVeriloglang="systemverilog">module rotate(in, out, shift);
 
parameter BITS = 32;
Line 5,725 ⟶ 6,135:
always_comb foreach (out[i]) out[i] = in[ (i+shift) % BITS ];
 
endmodule</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="tailspin">
def a: [x f075 x];
def b: [x 81 x];
Line 5,744 ⟶ 6,153:
$a::shift&{left: 3, fill: $a} -> '$a; rotated left 3 bits is $;$#10;' -> !OUT::write
$a::shift&{left: -3, fill: $a} -> '$a; rotated right 3 bits is $;$#10;' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,757 ⟶ 6,166:
f075 rotated right 3 bits is be0e
</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight 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,766 ⟶ 6,174:
puts [format "a << b: %#08x" [expr {$a << $b}]]
puts [format "a >> b: %#08x" [expr {$a >> $b}]]
}</langsyntaxhighlight>
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):
<langsyntaxhighlight lang="tcl">proc bitwiseUnsupported {a b} {
set bits 0xFFFFFFFF
# Force interpretation as a 32-bit unsigned value
Line 5,780 ⟶ 6,188:
(($a >> (32-$b)) & ($bits ^ ($bits << $b)))
}]]
}</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
Line 5,788 ⟶ 6,195:
The right shift operation fills the new leftmost bit with a copy of the old leftmost bit.
 
<langsyntaxhighlight lang="ti89b">bitwise(a,b)
Prgm
Local show, oldbase
Line 5,810 ⟶ 6,217:
show("RRo ", rotate(a,–b))
setMode("Base",oldbase)
EndPrgm</langsyntaxhighlight>
=={{header|Uxntal}}==
<syntaxhighlight lang="Uxntal">|00 @System [ &vector $2 &wst $1 &rst $1 &eaddr $2 &ecode $1 &pad $1 &r $2 &g $2 &b $2 &debug $1 &halt $1 ]
|10 @Console [ &vector $2 &read $1 &pad $5 &write $1 &error $1 ]
 
( program )
|0100 @on-reset ( -> )
#0a02
DUP2 SWP ;Labels/a <print-arg> ;Labels/b <print-arg>
bitwise
halt
BRK
 
@bitwise ( a b -- )
;Labels/not <print-str> ;Labels/a <print-str> ;Labels/equ <print-str> DUP2 [ POP #ff EOR ] <print-result>
;Labels/and <print-label> DUP2 [ AND ] <print-result>
;Labels/or <print-label> DUP2 [ ORA ] <print-result>
;Labels/xor <print-label> DUP2 [ EOR ] <print-result>
;Labels/shl <print-label> DUP2 [ #40 SFT SFT ] <print-result>
;Labels/shr <print-label> DUP2 [ SFT ] <print-result>
;Labels/rol <print-label> DUP2 [ #40 SFT #00 ROT ROT SFT2 ORA ] <print-result>
;Labels/ror <print-label> [ SWP #00 ROT SFT2 ORA ] <print-result>
JMP2r
 
@halt ( -- )
#01 .System/halt DEO
BRK
 
@<print-arg> ( a name* -- )
<print-str> ;Labels/equ <print-str> <print-result>
JMP2r
 
@<print-result> ( a -- )
<print-hex> ;Labels/newline <print-str>
JMP2r
 
@<print-label> ( label* -- )
;Labels/a <print-str>
<print-str>
;Labels/b <print-str>
;Labels/equ <print-str>
JMP2r
 
@<print-hex> ( byte -- )
[ LIT "$ ] .Console/write DEO
DUP #04 SFT <print-hex>/l
&l ( -- )
#0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO
JMP2r
 
@<print-str> ( str* -- )
&while ( -- )
LDAk .Console/write DEO
INC2 LDAk ?&while
POP2 JMP2r
 
@Labels
&a "a 20 $1
&b "b 20 $1
&equ "= 20 $1
&newline 0a $1
&not "NOT 20 $1
&and "AND 20 $1
&or "OR 20 $1
&xor "XOR 20 $1
&shl "SHL 20 $1
&shr "SHR 20 $1
&rol "ROL 20 $1
&ror "ROR 20 $1
</syntaxhighlight>
{{out}}
<pre>a = $0a
b = $02
NOT a = $f5
a AND b = $02
a OR b = $0a
a XOR b = $08
a SHL b = $28
a SHR b = $02
a ROL b = $28
a ROR b = $82
</pre>
 
=={{header|Vala}}==
<langsyntaxhighlight Valalang="vala">void testbit(int a, int b) {
print(@"input: a = $a, b = $b\n");
print(@"AND: $a & $b = $(a & b)\n");
Line 5,829 ⟶ 6,317:
int b = 2;
testbit(a,b);
}</langsyntaxhighlight>
{{out}}
<pre>input: a = 255, b = 2
Line 5,839 ⟶ 6,327:
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").
 
<langsyntaxhighlight 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,849 ⟶ 6,336:
Debug.Print Hex(&HF0F0 Eqv &HFF00) 'F00F
Debug.Print Hex(&HF0F0 Imp &HFF00) 'FF0F
</syntaxhighlight>
</lang>
 
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.
 
<langsyntaxhighlight lang="vb">Function MaskL(k As Integer) As Long
If k < 1 Then
MaskL = 0
Line 5,931 ⟶ 6,418:
Function TestBit(n As Long, k As Integer) As Boolean
TestBit = (n And Bit(k)) <> 0
End Function</langsyntaxhighlight>
 
Examples
 
<langsyntaxhighlight lang="vb">Debug.Print Hex(MaskL(8)) 'FF000000
Debug.Print Hex(MaskR(8)) 'FF
Debug.Print Hex(Bit(7)) '80
Line 5,946 ⟶ 6,433:
Debug.Print Hex(RotateR(65535, 8)) 'FF0000FF
Debug.Print Hex(RotateR(65535, -8)) 'FFFF00
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
identical syntax as in [[#VBA]].
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Sub Test(a as Integer, b as Integer)
WriteLine("And " & a And b)
WriteLine("Or " & a Or b)
Line 5,960 ⟶ 6,445:
WriteLine("Left Shift " & a << 2)
WriteLine("Right Shift " & a >> 2)
End Sub</langsyntaxhighlight>
 
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 5,972 ⟶ 6,456:
 
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.
<langsyntaxhighlight ecmascriptlang="wren">var rl = Fn.new { |x, y| x << y | x >> (32-y) }
 
var rr = Fn.new { |x, y| x >> y | x << (32-y) }
Line 5,992 ⟶ 6,476:
}
 
bitwise.call(10, 2)</langsyntaxhighlight>
 
{{out}}
Line 6,011 ⟶ 6,495:
{{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)
<langsyntaxhighlight lang="asm"> extern printf
global main
Line 6,114 ⟶ 6,598:
_null db 0
 
end</langsyntaxhighlight>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">
PROGRAM "bitwise"
 
Line 6,160 ⟶ 6,643:
END FUNCTION
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,185 ⟶ 6,668:
10101 Rotr 11: 10100000000000000000000000000010
</pre>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(defun bitwise-operations (a b)
; rotate operations are not supported
(print `(,a and ,b = ,(logand a b)))
Line 6,194 ⟶ 6,676:
(print `(,a left shift by ,b = ,(lsh a b)))
(print `(,a right shift by ,b = ,(lsh a (- b)))) ; negative second operand shifts right
(print `(,a arithmetic right shift by ,b = ,(ash a (- b)))) )</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="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,208 ⟶ 6,689:
func ROR(A, B); int A, B; return A>>B ! A<<(32-B);
 
Text(0, "A ror B = "); HexOut(0, ROR(A,B)); CrLf(0);</langsyntaxhighlight>
 
The reason the "!" and "|" symbols may seem reversed is that the OR
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}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub formBin$(n)
return right$("00000000" + bin$(n), 8)
end sub
Line 6,226 ⟶ 6,706:
print "OR = \t", formBin$(or(a, b))
print "XOR = \t", formBin$(xor(a, b))
print "NOT ", a, " =\t", formBin$(xor(255, a))</langsyntaxhighlight>
<pre>6 = 00000110
3 = 00000011
Line 6,234 ⟶ 6,714:
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>
 
Z80 has two different types of bit rotates.
* <code>RL/RR</code> rotates through the carry. The state of the carry before the rotate gets rotated in, and the bit that rotates out is put into the carry.
* <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
 
LD A,&05
RRA
 
LD A,&05
RLCA
 
LD A,&05
RRCA</syntaxhighlight>
=={{header|zkl}}==
No bitwise rotates. Shifts are unsigned.
<langsyntaxhighlight lang="zkl">(7).bitAnd(1) //-->1
(8).bitOr(1) //-->9
(7).bitXor(1) //-->6
Line 6,244 ⟶ 6,767:
(7).shiftLeft(1) //-->0xe
(-1).toString(16) //-->ffffffffffffffff
(-1).shiftRight(1).toString(16) //-->7fffffffffffffff</langsyntaxhighlight>
 
 
{{omit from|bc|No built-in bitwise operations}}
{{omit from|dc|No built-in bitwise operations}}
2,442

edits