Bitwise operations: Difference between revisions

m
m (syntax highlighting fixup automation)
 
(30 intermediate revisions by 16 users not shown)
Line 9:
If any operation is not available in your language, note it.
<br><br>
 
=={{header|11l}}==
{{trans|Kotlin}}
<syntaxhighlight lang="11l">V x = 10
V y = 2
print(‘x = ’x)
print(‘y = ’y)
print(‘NOT x = ’(-)~x))
print(‘x AND y = ’(x [&] y))
print(‘x OR y = ’(x [|] y))
Line 39 ⟶ 38:
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Bitwise operations 15/02/2017
BITWISE CSECT
USING BITWISE,R13
Line 138 ⟶ 137:
Bitwise operations are done using the accumulator and an immediate constant (prefixed with #) or a value at a specified memory location (no #.)
 
<syntaxhighlight lang="6502asm">LDA #$05
STA temp ;temp equals 5 for the following</syntaxhighlight>
 
;AND
<syntaxhighlight lang="6502asm">LDA #$08
AND temp</syntaxhighlight>
 
;OR
<syntaxhighlight lang="6502asm">LDA #$08
ORA temp</syntaxhighlight>
 
;XOR
<syntaxhighlight lang="6502asm">LDA #$08
EOR temp</syntaxhighlight>
 
;NOT
<syntaxhighlight lang="6502asm">LDA #$08
EOR #255</syntaxhighlight>
 
The 6502 doesn't have arithmetic shift right, but it can be replicated, provided the negative flag is set according to the value in the accumulator.
<syntaxhighlight lang="6502asm"> LDA #$FF
CLC ;clear the carry. That way, ROR will not accidentally shift a 1 into the top bit of a positive number
BPL SKIP
Line 167 ⟶ 166:
The 6502 can only rotate a value by one, not an arbitrary number. A looping routine is needed for rotates larger than 1.
Also, the 6502's <code>ROL</code> and <code>ROR</code> rotate instructions both rotate through the carry, unlike the instructions on other architectures with the same name. (68000, x86, and ARM all have a "ROR" command but it doesn't rotate through the carry on those CPUs.)
<syntaxhighlight lang="6502asm">LDA #$01
ROL ;if the carry was set prior to the ROL, A = 3. If the carry was clear, A = 2.</syntaxhighlight>
 
<syntaxhighlight lang="6502asm">LDA #$01
ROR ;if the carry was set prior to the ROR, A = 0x80. If clear, A = 0.</syntaxhighlight>
 
=={{header|68000 Assembly}}==
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation.
;AND
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0
MOVE.W #$200,D1
AND.W D0,D1</syntaxhighlight>
 
;OR
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0
MOVE.W #$200,D1
OR.W D0,D1</syntaxhighlight>
 
;XOR
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0
MOVE.W #$200,D1
EOR.W D0,D1</syntaxhighlight>
 
;NOT
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0
NOT.W D0</syntaxhighlight>
 
;Left Shift
<syntaxhighlight lang=68000devpac>MOVE.W #$FF,D0
MOVE.W #$04,D1
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</syntaxhighlight>
 
;Right Shift
<syntaxhighlight lang=68000devpac>MOVE.W #$FF,D0
MOVE.W #$04,D1
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</syntaxhighlight>
 
;Arithmetic Right Shift
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</syntaxhighlight>
 
;Left Rotate
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROL.W D1,D0</syntaxhighlight>
 
;Right Rotate
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROR.W D1,D0</syntaxhighlight>
 
;Left Rotate Through Extend Flag
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXL.W D1,D0</syntaxhighlight>
 
;Right Rotate Through Extend Flag
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXR.W D1,D0</syntaxhighlight>
 
=={{header|8051 Assembly}}==
Integer one is assumed to be a, integer two assumed to be b.
Line 234 ⟶ 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.
<syntaxhighlight lang="asm">; bitwise AND
anl a, b
 
Line 286 ⟶ 228:
rr a
djnz b, loop</syntaxhighlight>
 
=={{header|8086 Assembly}}==
;AND
<syntaxhighlight lang="asm">MOV AX,0345h
MOV BX,0444h
AND AX,BX</syntaxhighlight>
 
;OR
<syntaxhighlight lang="asm">MOV AX,0345h
MOV BX,0444h
OR AX,BX</syntaxhighlight>
 
;XOR
<syntaxhighlight lang="asm">MOV AX,0345h
MOV BX,0444h
XOR AX,BX</syntaxhighlight>
 
;NOT
<syntaxhighlight lang="asm">MOV AX,0345h
NOT AX</syntaxhighlight>
 
;Left Shift
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
SHL AX,CL</syntaxhighlight>
 
;Right Shift
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
SHR AX,CL</syntaxhighlight>
 
;Arithmetic Right Shift
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
SAR AX,CL</syntaxhighlight>
 
;Left Rotate
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
ROL AX,CL</syntaxhighlight>
 
;Right Rotate
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
ROR AX,CL</syntaxhighlight>
 
;Left Rotate Through Carry
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
RCL AX,CL</syntaxhighlight>
 
;Right Rotate Through Carry
<syntaxhighlight lang="asm">MOV AX,03h
MOV CL,02h
RCR AX,CL</syntaxhighlight>
=={{header|68000 Assembly}}==
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation.
;AND
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0
MOVE.W #$200,D1
AND.W D0,D1</syntaxhighlight>
 
;OR
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0
MOVE.W #$200,D1
OR.W D0,D1</syntaxhighlight>
 
;XOR
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0
MOVE.W #$200,D1
EOR.W D0,D1</syntaxhighlight>
 
;NOT
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0
NOT.W D0</syntaxhighlight>
 
;Left Shift
<syntaxhighlight lang="68000devpac">MOVE.W #$FF,D0
MOVE.W #$04,D1
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</syntaxhighlight>
 
;Right Shift
<syntaxhighlight lang="68000devpac">MOVE.W #$FF,D0
MOVE.W #$04,D1
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</syntaxhighlight>
 
;Arithmetic Right Shift
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</syntaxhighlight>
 
;Left Rotate
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROL.W D1,D0</syntaxhighlight>
 
;Right Rotate
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROR.W D1,D0</syntaxhighlight>
 
;Left Rotate Through Extend Flag
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXL.W D1,D0</syntaxhighlight>
 
;Right Rotate Through Extend Flag
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0
MOVE.W #$04,D1
ROXR.W D1,D0</syntaxhighlight>
=={{header|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"abap">
report z_bitwise_operations.
 
Line 639 ⟶ 809:
a rotr b -> C000003F, 11000000000000000000000000111111, -1073741761
</pre>
 
=={{header|ACL2}}==
Unlisted operations are not available
<syntaxhighlight lang=Lisp"lisp">(defun bitwise (a b)
(list (logand a b)
(logior a b)
Line 649 ⟶ 818:
(ash a b)
(ash a (- b))))</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">BYTE FUNC Not(BYTE a)
RETURN (a!$FF)
 
Line 685 ⟶ 853:
127 SHL 2 = 252
</pre>
 
=={{header|ActionScript}}==
ActionScript does not support bitwise rotations.
<syntaxhighlight lang=ActionScript"actionscript">function bitwise(a:int, b:int):void
{
trace("And: ", a & b);
Line 698 ⟶ 865:
trace("Right Shift(Logical): ", a >>> b);
}</syntaxhighlight>
 
=={{header|Ada}}==
The following program performs all required operations and prints the resulting values in base 2 for easy checking of the bit values.
 
<syntaxhighlight lang="ada">with Ada.Text_IO, Interfaces;
use Ada.Text_IO, Interfaces;
 
Line 725 ⟶ 891:
Put_Line (Unsigned_8'Image (Rotate_Right (X, N)));
end Bitwise;</syntaxhighlight>
 
=={{header|Aikido}}==
{{trans|Javascript}}
 
There is no rotate support built in to Aikido.
<syntaxhighlight lang="aikido">function bitwise(a, b){
println("a AND b: " + (a & b))
println("a OR b: "+ (a | b))
Line 739 ⟶ 904:
println("a >>> b: " + (a >>> b)) // logical right shift
}</syntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Standard - no extensions to language used}}
Line 747 ⟶ 911:
* 2r00000000000000000000000010101010, 4r0000000000002222, 8r00000000252, 16r000000aa
* and as an array of BOOL: FFFFFFFFFFFFFFFFFFFFFFFFTFTFTFTF
<syntaxhighlight lang="algol68">main:(
 
PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here #
Line 836 ⟶ 1,000:
</pre>
Note that an INT can be widened into BITS, and BITS can be widened into an array of BOOL. eg:
<syntaxhighlight lang="algol68"># unpack (widen) some data back into an a BOOL array #
INT i := 170;
BITS j := BIN i;
Line 854 ⟶ 1,018:
+85, 8r0125, FTFTFTFT
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">% performs bitwise and, or, not, left-shift and right shift on the integers n1 and n2 %
% Algol W does not have xor, arithmetic right shift, left rotate or right rotate %
procedure bitOperations ( integer value n1, n2 ) ;
Line 875 ⟶ 1,038:
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" )
end bitOPerations ;</syntaxhighlight>
 
=={{header|AppleScript}}==
Applescript has no bitwise operators. It's probably not the right tool to reach for if you need to work with bits.
Line 893 ⟶ 1,055:
 
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,264 ⟶ 1,426:
 
'''Second option''' – writing our own bitwise functions for Applescript:
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 1,771 ⟶ 1,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.
 
<syntaxhighlight lang="applescript">on bitwiseAND(n1, n2, registerSize)
set out to 0
-- Multiplying equivalent bit values by each other gives 1 where they're both 1 and 0 otherwise.
Line 1,853 ⟶ 2,015:
rightRotate(92, 7, 8) --> 184
rightRotate(92, 7, 16) --> 47104</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
 
/* ARM assembly Raspberry PI */
Line 2,019 ⟶ 2,180:
 
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">a: 255
b: 2
 
Line 2,039 ⟶ 2,199:
255 SHL 2 = 1020
255 SHR 2 = 63 </pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey"autohotkey">bitwise(3, 4)
bitwise(a, b)
{
Line 2,051 ⟶ 2,210:
MsgBox % "a >> b: " . a >> b ; arithmetic right shift
}</syntaxhighlight>
 
=={{header|AutoIt}}==
No arithmetic shift.
<syntaxhighlight lang=AutoIt"autoit">bitwise(255, 5)
Func bitwise($a, $b)
MsgBox(1, '', _
Line 2,077 ⟶ 2,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 2,083 ⟶ 2,240:
{{works with|gawk}}
 
<syntaxhighlight lang="awk">BEGIN {
n = 11
p = 1
Line 2,095 ⟶ 2,252:
 
[[OpenBSD]] <code>/usr/bin/awk</code> (a variant of [[nawk]]) has these same functions, with a few differences. Gawk uses 53-bit unsigned integers, but OpenBSD awk uses 32-bit signed integers. Therefore Gawk prints <code>not 11 = 0x1ffffffffffff4</code>, but OpenBSD awk prints <code>not 11 = 0xfffffff4</code>.
 
=={{header|Axe}}==
<syntaxhighlight lang="axe">Lbl BITS
r₁→A
r₂→B
Line 2,108 ⟶ 2,264:
 
Note that the symbols for AND, OR, and XOR are the stat plot marks near the bottom of the Catalog.
 
=={{header|Babel}}==
 
In Babel, we prefix the logic operators with a 'c' to denote that they are C-style operations, that is, they are word-width operations, not arbitrary size operations. The following program combines the numbers 5 and 9 using the various bitwise operators and then displays the results.
 
<syntaxhighlight lang="babel">({5 9}) ({cand} {cor} {cnor} {cxor} {cxnor} {shl} {shr} {ashr} {rol}) cart ! {give <- cp -> compose !} over ! {eval} over ! {;} each</syntaxhighlight>
 
{{Out}}
Line 2,128 ⟶ 2,283:
The cnot operator works on just one operand:
 
<syntaxhighlight lang="babel">9 cnot ;</syntaxhighlight>
 
{{Out}}
<pre>[val 0xfffffff6 ]</pre>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
QuickBasic does not have shift or rotate operations defined. Here are the logical operations:
<syntaxhighlight lang="qbasic">SUB bitwise (a, b)
PRINT a AND b
PRINT a OR b
Line 2,145 ⟶ 2,299:
{{works with|FreeBASIC}}
FreeBASIC does not have rotate operators. Shift Right operator performs arithmetic shift if the left value is signed number and logical shift if the left value is unsigned number.
<syntaxhighlight lang="freebasic">SUB bitwise (a AS Integer, b AS Integer)
DIM u AS UInteger
 
Line 2,161 ⟶ 2,315:
Commodore BASIC V2.0 does not have '''XOR''', '''left shift''', '''right shift''', '''right arithmetic shift''', '''left rotate''', and '''right rotate''' operators. In this implementation the '''XOR''' operation is done with an equivalent formula.
 
<syntaxhighlight lang="basic">10 INPUT "A="; A
20 INPUT "B="; B
30 PRINT "A AND B =" A AND B :rem AND
Line 2,178 ⟶ 2,332:
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang=IS"is-BASICbasic">100 LET A=10:LET B=12
110 PRINT A;"and";B;"=";A AND B
120 PRINT A;"band";B;"=";A BAND B
Line 2,193 ⟶ 2,347:
 
The disassembly of the Z80 code would be:
<syntaxhighlight lang="z80asm"> org 4084
3a 83 40 ld a, (4083)
47 ld b, a
Line 2,208 ⟶ 2,362:
Finally, observe that the first line reserves 15 bytes for our machine code routine by hiding them in a comment.
 
<syntaxhighlight lang="basic"> 10 REM ABCDEFGHIJKLMNO
20 INPUT A
30 INPUT B
Line 2,246 ⟶ 2,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.
 
<syntaxhighlight lang="tinybasic">
REM VARIABLES
REM A = first number
Line 2,327 ⟶ 2,481:
GOTO 500
</syntaxhighlight>
==={{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}}==
<syntaxhighlight lang=BASIC256"basic256"># bitwise operators - floating point numbers will be cast to integer
a = 0b00010001
b = 0b11110000
Line 2,337 ⟶ 2,525:
print a | b # bitwise or on two integer values
print a & b # bitwise or on two integer values</syntaxhighlight>
 
=={{header|Batch File}}==
The SET command with the /A option supports arithmetic and bit operations on signed 8 byte integers.
Line 2,344 ⟶ 2,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.
<syntaxhighlight lang="dos">
@echo off
setlocal
Line 2,463 ⟶ 2,650:
11111101000000000000000000000001
</pre>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> number1% = &89ABCDEF
number2% = 8
Line 2,477 ⟶ 2,663:
PRINT ~ (number1% << number2%) OR (number1% >>> (32-number2%)) : REM left rotate
PRINT ~ (number1% >>> number2%) OR (number1% << (32-number2%)) : REM right rotate</syntaxhighlight>
 
=={{header|beeswax}}==
<syntaxhighlight lang="beeswax">#eX~T~T_#
###>N{` AND `~{~` = `&{Nz1~3J
UXe#
Line 2,506 ⟶ 2,691:
 
Example:
<syntaxhighlight lang=Julia"julia">
julia> beeswax("Bitops.bswx",0,0.0,Int(20000))
i9223653511831486512
Line 2,530 ⟶ 2,715:
 
Arithmetic shift right is not originally implemented in beeswax because it does not make sense for unsigned integers, but for negative numbers, it can be realized easily with
<syntaxhighlight lang="beeswax">A>>B = NOT(NOT(A)>>>B)</syntaxhighlight>
as demonstrated above.
 
In beeswax, rotate left (ROL) and rotate right (ROT) operators are implemented using modulo 64, so rotations by more than 63 bits wrap around:
 
<syntaxhighlight lang="beeswax">A ROL B = A<<(B%64)+A>>>(64-B%64)
A ROR B = A>>>(B%64)+A<<(64-B%64)</syntaxhighlight>
 
=={{header|Befunge}}==
<syntaxhighlight lang="befunge">> v MCR >v
1 2 3 4 5 6>61g-:| 8 9
>&&\481p >88*61p371p >:61g\`!:68*+71g81gp| 7 >61g2/61p71g1+71pv
Line 2,590 ⟶ 2,774:
1 22 23 106 42 10
</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">void bitwise(int a, int b)
{
printf("a and b: %d\n", a & b);
Line 2,608 ⟶ 2,791:
 
To rotate an integer, you can combine a left shift and a right shift:
<syntaxhighlight lang=C"c">/* rotate x to the right by s bits */
unsigned int rotr(unsigned int x, unsigned int s)
{
return (x >> s) | (x << 32 - s);
}</syntaxhighlight>With a smart enough compiler, the above actually compiles into a single machine bit rotate instruction when possible. E.g. <code>gcc -S</code> on IA32 produced following assembly code:<syntaxhighlight lang=Assembly"assembly">rotr:
movl 4(%esp), %eax ; arg1: x
movl 8(%esp), %ecx ; arg2: s
rorl %cl, %eax ; right rotate x by s
ret</syntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">static void bitwise(int a, int b)
{
Console.WriteLine("a and b is {0}", a & b);
Line 2,633 ⟶ 2,815:
// there are no rotation operators in C#
}</syntaxhighlight>
 
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <iostream>
 
void bitwise(int a, int b)
Line 2,659 ⟶ 2,840:
}</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="lisp">(bit-and x y)
(bit-or x y)
(bit-xor x y)
Line 2,668 ⟶ 2,848:
(bit-shift-right x n)
;;There is no built-in for rotation.</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang=cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. bitwise-ops.
 
Line 2,678 ⟶ 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,702 ⟶ 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
.</syntaxhighlight>
 
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.
<syntaxhighlight 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,726 ⟶ 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.
 
.</syntaxhighlight>
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
 
<syntaxhighlight lang="coffeescript">
f = (a, b) ->
p "and", a & b
Line 2,769 ⟶ 2,971:
 
output
<syntaxhighlight lang="text">
> coffee foo.coffee
and 2
Line 2,778 ⟶ 2,980:
>> 2
</syntaxhighlight>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">(defun bitwise (a b)
(print (logand a b)) ; AND
(print (logior a b)) ; OR ("ior" = inclusive or)
Line 2,792 ⟶ 2,993:
Left and right logical shift may be implemented by the following functions:
 
<syntaxhighlight lang="lisp">
(defun shl (x width bits)
"Compute bitwise left shift of x by 'bits' bits, represented on 'width' bits"
Line 2,806 ⟶ 3,007:
Left and right rotation may be implemented by the following functions:
 
<syntaxhighlight lang="lisp">
(defun rotl (x width bits)
"Compute bitwise left rotation of x by 'bits' bits, represented on 'width' bits"
Line 2,821 ⟶ 3,022:
(1- (ash 1 width)))))
</syntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">T rot(T)(in T x, in int shift) pure nothrow @nogc {
return (x >>> shift) | (x << (T.sizeof * 8 - shift));
}
Line 2,857 ⟶ 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}}==
<syntaxhighlight lang=Delphi"delphi">program Bitwise;
 
{$APPTYPE CONSOLE}
Line 2,873 ⟶ 3,072:
Readln;
end.</syntaxhighlight>
 
=={{header|DWScript}}==
<syntaxhighlight lang=Delphi"delphi">PrintLn('2 and 3 = '+IntToStr(2 and 3));
PrintLn('2 or 3 = '+IntToStr(2 or 3));
PrintLn('2 xor 3 = '+IntToStr(2 xor 3));
Line 2,881 ⟶ 3,079:
PrintLn('2 shl 3 = '+IntToStr(2 shl 3));
PrintLn('2 shr 3 = '+IntToStr(2 shr 3));</syntaxhighlight>
 
=={{header|E}}==
E provides arbitrary-size integers, so there is no distinct arithmetic and logical shift right. E does not provide bit rotate operations.
 
<syntaxhighlight lang="e">def bitwise(a :int, b :int) {
println(`Bitwise operations:
a AND b: ${a & b}
Line 2,895 ⟶ 3,092:
`)
}</syntaxhighlight>
=={{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"ecl">
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION
BitAND := A & B;
Line 2,928 ⟶ 3,137:
*/
</syntaxhighlight>
 
=={{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 :
<syntaxhighlight lang="elena">import extensions;
 
extension testOp
Line 2,937 ⟶ 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,961 ⟶ 3,227:
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Bitwise_operation do
use Bitwise
Line 3,002 ⟶ 3,268:
255 >>> 2 = 63
</pre>
 
=={{header|Erlang}}==
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate.
 
<syntaxhighlight lang="erlang">
-module(bitwise_operations).
 
Line 3,023 ⟶ 3,288:
 
outputs:
<syntaxhighlight lang="erlang">
255 band 170 = 170
255 bor 170 = 255
Line 3,031 ⟶ 3,296:
255 bsr 170 = 0
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">let bitwise a b =
printfn "a and b: %d" (a &&& b)
printfn "a or b: %d" (a ||| b)
Line 3,042 ⟶ 3,306:
printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift
// No rotation operators.</syntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">"a=" "b=" [ write readln string>number ] bi@
{
[ bitand "a AND b: " write . ]
Line 3,055 ⟶ 3,318:
 
outputs:
<syntaxhighlight lang="factor">a=255
b=5
a AND b: 5
Line 3,064 ⟶ 3,327:
a asr b: 7</syntaxhighlight>
Currently rotation and logical shifts are not implemented.
 
=={{header|FALSE}}==
Only AND, OR, and NOT are available.
<syntaxhighlight lang="false">10 3
\$@$@$@$@\ { 3 copies }
"a & b = "&."
Line 3,073 ⟶ 3,335:
~a = "%~."
"</syntaxhighlight>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">: arshift 0 ?do 2/ loop ; \ 2/ is an arithmetic shift right by one bit (2* shifts left one bit)
: bitwise ( a b -- )
cr ." a = " over . ." b = " dup .
Line 3,087 ⟶ 3,348:
2drop ;</syntaxhighlight>
Rotation is not standard, but may be provided in particular Forth implementations, or as an assembly instruction in CODE words.
 
=={{header|Fortran}}==
In ISO Fortran 90 and later the following BIT INTRINSIC functions are defined:
<syntaxhighlight lang="fortran">integer :: i, j = -1, k = 42
logical :: a
Line 3,118 ⟶ 3,378:
! arithmetically equivalent to: MOD((K / 2**7), 2**8)</syntaxhighlight>
The following INTRINSIC ELEMENTAL SUBROUTINE is also defined:
<syntaxhighlight lang="fortran"> call mvbits(k, 2, 4, j, 0) ! copy a sequence of 4 bits from k starting at bit 2 into j starting at bit 0</syntaxhighlight>
 
<syntaxhighlight lang="fortran">
program bits_rosetta
implicit none
Line 3,148 ⟶ 3,408:
</syntaxhighlight>
Output
<syntaxhighlight lang="text">
Input a= 14 b= 3
AND : 00000000000000000000000000001110 & 00000000000000000000000000000011 = 00000000000000000000000000000010 2
Line 3,158 ⟶ 3,418:
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823
</syntaxhighlight>
 
=={{header|Free Pascal}}==
<syntaxhighlight lang="pascal">program Bitwise;
{$mode objfpc}
var
Line 3,179 ⟶ 3,438:
Readln;
end.</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits)
 
Line 3,267 ⟶ 3,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)
 
def fn rotl( b as long, n as long ) as long = ( ( 2^n * b) mod 256) or (b > 127)
Line 3,313 ⟶ 3,570:
Rotate right : fn rotr( a, b ) = 11000000000000000000000000111111 : -1073741761
</pre>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 3,366 ⟶ 3,622:
rol: 1000110100111111
ror: 1101001111111000</pre>
 
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">def bitwise = { a, b ->
println """
a & b = ${a} & ${b} = ${a & b}
Line 3,381 ⟶ 3,636:
 
Program:
<syntaxhighlight lang="groovy">bitwise(-15,3)</syntaxhighlight>
 
Output:
Line 3,391 ⟶ 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.
<syntaxhighlight lang="visualfoxpro">
PROCEDURE Main(...)
local n1 := 42, n2 := 2
Line 3,454 ⟶ 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.
<syntaxhighlight lang="haskell">import Data.Bits
 
bitwise :: Int -> Int -> IO ()
Line 3,500 ⟶ 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
<syntaxhighlight lang="hicest">i = IAND(k, j)
i = IOR( k, j)
i = IEOR(k, j)
i = NOT( k )</syntaxhighlight>
 
=={{header|HPPPL}}==
<syntaxhighlight lang="hpppl">EXPORT BITOPS(a, b)
BEGIN
PRINT(BITAND(a, b));
Line 3,519 ⟶ 3,770:
// HPPPL has no builtin rotates or arithmetic right shift.
END;</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang=Icon"icon">procedure main()
bitdemo(255,2)
bitdemo(-15,3)
Line 3,565 ⟶ 3,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.
 
<syntaxhighlight lang=Inform"inform 6">[ bitwise a b temp;
print "a and b: ", a & b, "^";
print "a or b: ", a | b, "^";
Line 3,585 ⟶ 3,834:
];
</syntaxhighlight>
 
=={{header|J}}==
 
Here are the "[http://www.jsoftware.com/help/dictionary/dbdotn.htm bitwise operators]":
 
<syntaxhighlight lang="j">bAND=: 17 b. NB. 16+#.0 0 0 1
bOR=: 23 b. NB. 16+#.0 1 1 1
bXOR=: 22 b. NB. 16+#.0 1 1 0
Line 3,602 ⟶ 3,850:
And here is a routine which takes a list of bitwise operators and two numbers and displays a table of results from combining those two numbers with each of the operators:
 
<syntaxhighlight lang="j">bitwise=: 1 :0
:
smoutput (((":x),"1' ',.(>u),.' '),"1":y),"1' => ',"1'.X'{~#:x u`:0 y
Line 3,609 ⟶ 3,857:
And here they are in action:
 
<syntaxhighlight lang="j"> 254 bAND`bOR`bXOR`b1NOT`bLshift`bRshift`bRAshift`bLrot`bRrot bitwise 3
254 bAND 3 => ............................X.
254 bOR 3 => ......................XXXXXXXX
Line 3,621 ⟶ 3,869:
 
Further test
<syntaxhighlight lang="j">
bXOR/ 3333 5555 7777 9999
8664
</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">public static void bitwise(int a, int b){
System.out.println("a AND b: " + (a & b));
System.out.println("a OR b: "+ (a | b));
Line 3,639 ⟶ 3,886:
}</syntaxhighlight>
All of the operators may be combined with the <tt>=</tt> operator to save space. For example, the following lines each do the same thing:
<syntaxhighlight lang="java">a <<= 3;
a = a << 3;
a *= 8; //2 * 2 * 2 = 8
a = a * 8;</syntaxhighlight>
 
=={{header|JavaScript}}==
There are no integers in Javascript, but there are still bitwise operators. They will convert their number operands into integers before performing they task. In other languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow and rarely used.
 
<syntaxhighlight lang="javascript">function bitwise(a, b){
alert("a AND b: " + (a & b));
alert("a OR b: "+ (a | b));
Line 3,656 ⟶ 3,902:
alert("a >>> b: " + (a >>> b)); // logical right shift
}</syntaxhighlight>
=={{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}}==
<syntaxhighlight lang="julia"># Version 5.2
@show 1 & 2 # AND
@show 1 | 2 # OR
Line 3,691 ⟶ 3,996:
 
=={{header|Kotlin}}==
<syntaxhighlight lang=scala"kotlin">/* 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)}")
}</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
Line 3,731 ⟶ 4,034:
 
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate.
<syntaxhighlight lang="lisp">(defun bitwise (a b)
(lists:map
(lambda (x) (io:format "~p~n" `(,x)))
Line 3,760 ⟶ 4,063:
 
Example usage:
<syntaxhighlight lang="lisp">
> (bitwise 255 170)
170
Line 3,779 ⟶ 4,082:
>
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
Written as functions.
<syntaxhighlight lang="lb">
' bitwise operations on byte-sized variables
 
Line 3,830 ⟶ 4,132:
end function
</syntaxhighlight>
 
=={{header|Lingo}}==
Lingo has built-in functions for bitwise AND, OR, XOR and NOT:
<syntaxhighlight lang="lingo">put bitAND(2,7)
put bitOR(2,7)
put bitXOR(2,7)
put bitNOT(7)</syntaxhighlight>
Bit shifting and rotating has to be implemented by custom functions.
 
=={{header|LiveCode}}==
<syntaxhighlight lang=LiveCode"livecode">put "and:" && (255 bitand 2) & comma into bitops
put " or:" && (255 bitor 2) & comma after bitops
put " xor:" && (255 bitxor 2) & comma after bitops
Line 3,849 ⟶ 4,149:
and: 2, or: 255, xor: 253, not: 4294967040</syntaxhighlight>
LiveCode does not provide built-in bit-shift operations.
 
=={{header|LLVM}}==
<syntaxhighlight lang="llvm">; ModuleID = 'test.o'
;e means little endian
;p: { pointer size : pointer abi : preferred alignment for pointers }
Line 3,911 ⟶ 4,210:
;Declare external fuctions
declare i32 @printf(i8* nocapture, ...) nounwind</syntaxhighlight>
 
=={{header|Logo}}==
{{works with|UCB Logo}}
<syntaxhighlight lang="logo">to bitwise :a :b
(print [a and b:] BitAnd :a :b)
(print [a or b:] BitOr :a :b)
Line 3,926 ⟶ 4,224:
bitwise 255 5</syntaxhighlight>
The output of this program is:
<syntaxhighlight lang="logo">a and b: 5
a or b: 255
a xor b: 250
Line 3,933 ⟶ 4,231:
a lshift -b: 7
-a ashift -b: -8</syntaxhighlight>
 
=={{header|LSE64}}==
{{incorrect|LSE64|No reason given.}}
<syntaxhighlight lang="lse64">over : 2 pick
2dup : over over
Line 3,947 ⟶ 4,244:
\ a \ 7 bitwise # hex literals</syntaxhighlight>
 
=={{header|Lua}}==
 
LuaBitOp implements bitwise functionality for Lua:
 
<syntaxhighlight lang="lua">local bit = require"bit"
 
local vb = {
Line 4,025 ⟶ 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:
<syntaxhighlight lang="lua">a = 0xAA55AA55
b = 0x4
print(string.format("%8X and %8X = %16X", a, b, a&b))
Line 4,050 ⟶ 4,346:
AA55AA55 rol 4 = A55AA55A
AA55AA55 ror 4 = 5AA55AA5</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang=Maple"maple">
with(Bits):
bit:=proc(A,B)
Line 4,072 ⟶ 4,367:
end proc;
</syntaxhighlight>
 
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
Most functions are built-in or can be made really easily:
<syntaxhighlight lang=Mathematica"mathematica">(*and xor and or*)
BitAnd[integer1, integer2]
BitXor[integer1, integer2]
Line 4,094 ⟶ 4,388:
FromDigits[Prepend[Most[#], #[[1]]], 2] &[IntegerDigits[integer1, 2]]</syntaxhighlight>
The function BitShiftLeft, BitShiftRight, RotateRight, RotateLeft all take a second argument, which is the displacement, by default it is set to 1. BitAnd, BitXor and BitOr can handle more than 2 arguments:
<syntaxhighlight lang=Mathematica"mathematica">BitXor[3333, 5555, 7777, 9999]</syntaxhighlight>
gives back:
<syntaxhighlight lang=Mathematica"mathematica">8664</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Newer versions of MATLAB have even more bitwise operations than those demonstrated here. A complete list of bitwise operations for the newest version of MATLAB can be found at [http://www.mathworks.com/help/toolbox/fixedpoint/ref/f20333.html#bp7caxc-42 MathWorks]
 
<syntaxhighlight lang=MATLAB"matlab">function bitwiseOps(a,b)
 
disp(sprintf('%d and %d = %d', [a b bitand(a,b)]));
Line 4,112 ⟶ 4,405:
 
Output:
<syntaxhighlight lang=MATLAB"matlab">>> bitwiseOps(255,2)
255 and 2 = 2
255 or 2 = 255
Line 4,118 ⟶ 4,411:
255 << 2 = 1020
255 >> 2 = 63</syntaxhighlight>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">load(functs)$
 
a: 3661$
Line 4,143 ⟶ 4,435:
logand(a, -a - 1);
/* 0 */</syntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">fn bitwise a b =
(
format "a and b: %\n" (bit.and a b)
Line 4,158 ⟶ 4,449:
 
MAXScript doesn't have arithmetic shift or rotate operations.
 
=={{header|ML/I}}==
ML/I only supports bitwise AND and OR operations. These are available from version CKD onwards.
 
<syntaxhighlight lang=ML"ml/Ii">MCSKIP "WITH" NL
"" Bitwise operations
"" assumes macros on input stream 1, terminal on stream 2
Line 4,178 ⟶ 4,468:
*MCSET S10=2
</syntaxhighlight>
 
=={{header|Modula-3}}==
 
<syntaxhighlight lang="modula3">MODULE Bitwise EXPORTS Main;
 
IMPORT IO, Fmt, Word;
Line 4,215 ⟶ 4,504:
c RightRotate b: f8000007
</pre>
 
=={{header|Neko}}==
<syntaxhighlight lang=ActionScript"actionscript">/**
<doc>
<h2>bitwise operations</h2>
Line 4,299 ⟶ 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}}==
<syntaxhighlight lang=Nemerle"nemerle">def i = 255;
def j = 2;
 
Line 4,314 ⟶ 4,601:
// the operator performs a logical shift right
// there are no rotation operators in Nemerle, but you could define your own w/ a macro if you really wanted it</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc bitwise(a, b) =
echo "a and b: " , a and b
echo "a or b: ", a or b
Line 4,323 ⟶ 4,609:
echo "a << b: ", a shl b
echo "a >> b: ", a shr b</syntaxhighlight>
 
=={{header|NSIS}}==
All bitwise operations in NSIS are handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 IntOp] instruction.
<syntaxhighlight lang="nsis">Function Bitwise
Push $0
Push $1
Line 4,353 ⟶ 4,638:
Pop $0
FunctionEnd</syntaxhighlight>
 
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<syntaxhighlight lang="oberon2">
MODULE Bitwise;
IMPORT
Line 4,398 ⟶ 4,682:
a arithmetic right shift b :> 2
</pre>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">use IO;
 
bundle Default {
Line 4,417 ⟶ 4,700:
}
}</syntaxhighlight>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let bitwise a b =
Printf.printf "a and b: %d\n" (a land b);
Printf.printf "a or b: %d\n" (a lor b);
Line 4,428 ⟶ 4,710:
Printf.printf "a lsr b: %d\n" (a lsr b); (* logical right shift *)
;;</syntaxhighlight>
 
=={{header|Octave}}==
 
There's no arithmetic shift nor rotation (and the not can be done through a xor)
 
<syntaxhighlight lang="octave">function bitops(a, b)
s = sprintf("%s %%s %s = %%s\n", dec2bin(a), dec2bin(b));
printf(s, "or", dec2bin(bitor(a, b)));
Line 4,444 ⟶ 4,725:
 
bitops(0x1e, 0x3);</syntaxhighlight>
 
=={{header|Oforth}}==
 
There is no built-in for not and rotation
 
<syntaxhighlight lang=Oforth"oforth">: bitwise(a, b)
a b bitAnd println
a b bitOr println
Line 4,455 ⟶ 4,735:
a bitLeft(b) println
a bitRight(b) println ;</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx"oorexx">/* ooRexx *************************************************************
/ Bit Operations work as in Rexx (of course)
* Bit operations are performed up to the length of the shorter string.
Line 4,487 ⟶ 4,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>.
<syntaxhighlight lang="parigp">bo(a,b)={
print("And: "bitand(a,b));
print("Or: "bitor(a,b));
Line 4,502 ⟶ 4,779:
print("Right shift: ",a>>b);
}</syntaxhighlight>
 
=={{header|Pascal}}==
While Standard Pascal does not have bitwise operations, most Pascal implementations (including Turbo Pascal and Delphi) extend the standard logical operators to also provide bitwise operations:
<syntaxhighlight lang="pascal">var
a, b: integer;
begin
Line 4,514 ⟶ 4,790:
writeln('a xor b = ', a xor b) { 6 = 0110 }
end.</syntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use integer;
sub bitwise :prototype($$) {
($a, $b) = @_;
print 'a and b: '. ($a & $b) ."\n";
Line 4,534 ⟶ 4,809:
=={{header|Phix}}==
Phix has four builtin bitwise operations (and/or/xor/not)_bits, which each have sequence and unsigned variants. Note careful use of latter (unsigned) routines here, since Phix naturally preserves signs (and common sense) when it can, rather than rudely treat, for instance, +4,294,967,295 as -1, unless explicitly told to do so as it is below. Likewise the builtin shift operators deliver signed and unbounded results, so we'll wrap them here. There are no builtin rotate routines, but easy enough to devise. The distributed copy (1.0.2+) also contains an (older) inline assembly version, which is obviously not JavaScript compatible, but may be significantly faster, for desktop-only applications.
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Bitwise_operations.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 4,586 ⟶ 4,861:
ror(10000000000000000000000011111110,111) = 11111101000000000000000000000001
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">6 var a 3 var b
 
def tab
Line 4,605 ⟶ 4,879:
"XOR = " print tab a b bitxor printBits
"NOT = " print tab a bitnot printBits</syntaxhighlight>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">function bitwise($a, $b)
{
function zerofill($a,$b) {
Line 4,622 ⟶ 4,895:
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift
}</syntaxhighlight>
 
=={{header|PicoLisp}}==
PicoLisp has no specific word size. Numbers grow to arbitrary length. Therefore,
Line 4,629 ⟶ 4,901:
 
Bitwise AND:
<syntaxhighlight lang=PicoLisp"picolisp">: (& 6 3)
-> 2
 
Line 4,636 ⟶ 4,908:
Bitwise AND-Test (tests if all bits in the first argument are set in the
following arguments):
<syntaxhighlight lang=PicoLisp"picolisp">: (bit? 1 2)
-> NIL
 
Line 4,645 ⟶ 4,917:
-> 6</syntaxhighlight>
Bitwise OR:
<syntaxhighlight lang=PicoLisp"picolisp">: (| 1 2)
-> 3
 
Line 4,651 ⟶ 4,923:
-> 15</syntaxhighlight>
Bitwise XOR:
<syntaxhighlight lang=PicoLisp"picolisp">: (x| 2 7)
-> 5
 
Line 4,657 ⟶ 4,929:
-> 4</syntaxhighlight>
Shift (right with a positive count, left with a negative count):
<syntaxhighlight lang=PicoLisp"picolisp">: (>> 1 8)
-> 4
 
Line 4,668 ⟶ 4,940:
: (>> -1 -16)
-> -32</syntaxhighlight>
 
=={{header|Pike}}==
Rotate operations are not available
<syntaxhighlight lang=Pike"pike">
void bitwise(int a, int b)
{
Line 4,701 ⟶ 4,972:
a << b & 0xffffffff (32bit cap): 0xc0000000
</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">/* PL/I can perform bit operations on binary integers. */
k = iand(i,j);
k = ior(i,j);
Line 4,729 ⟶ 4,999:
u = substr(s, 2) || substr(s, 1, 1); /* implements rotate left. */
</syntaxhighlight>
 
=={{header|Pop11}}==
 
<syntaxhighlight lang="pop11">define bitwise(a, b);
printf(a && b, 'a and b = %p\n');
printf(a || b, 'a or b = %p\n');
Line 4,744 ⟶ 5,013:
 
Similarly, on infinitely precise numbers rotation is undefined.
 
=={{header|PowerShell}}==
Logical right shift and rotations are not supported in PowerShell.
{{works with|PowerShell|2.0}}
<syntaxhighlight lang=PowerShell"powershell">$X -band $Y
$X -bor $Y
$X -bxor $Y
Line 4,754 ⟶ 5,022:
{{works with|PowerShell|3.0}}
<syntaxhighlight lang=PowerShell"powershell">$X -shl $Y
# Arithmetic right shift
$X -shr $Y
Line 4,760 ⟶ 5,028:
# Requires quite a stretch of the imagination to call this "native" support of right rotate, but it works
[System.Security.Cryptography.SHA256Managed].GetMethod('RotateRight', 'NonPublic, Static', $null, @([UInt32], [Int32]), $null).Invoke($null, @([uint32]$X, $Y))</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">Procedure Bitwise(a, b)
Debug a & b ; And
Debug a | b ;Or
Line 4,791 ⟶ 5,058:
Debug Temp
EndProcedure</syntaxhighlight>
 
=={{header|Python}}==
===Python 3===
Line 4,800 ⟶ 5,066:
binary output formatting in calculations and result displays.
 
<syntaxhighlight lang="python">def bitwise_built_ins(width, a, b):
mask = (1 << width) - 1
print(f"""\
Line 4,966 ⟶ 5,232:
 
===Python 2===
<syntaxhighlight lang="python">def bitwise(a, b):
print 'a and b:', a & b
print 'a or b:', a | b
Line 4,978 ⟶ 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:
 
<syntaxhighlight lang="python"># 8-bit bounded shift:
x = x << n & 0xff
# ditto for 16 bit:
Line 4,989 ⟶ 5,255:
We can easily implement our own rotation functions. For left rotations this is down by ORing the left shifted and masked lower bits against the right shifted upper bits. For right rotations we perform the converse operations, ORing a set of right shifted lower bits against the appropriate number of left shifted upper bits.
 
<syntaxhighlight lang="python">def bitstr(n, width=None):
"""return the binary representation of n as a string and
optionally zero-fill (pad) it to a given length
Line 5,032 ⟶ 5,298:
 
In this example we show a relatively straightforward function for converting integers into strings of bits, and another simple ''mask()'' function to create arbitrary lengths of bits against which we perform our masking operations. Also note that the implementation of these functions defaults to single bit rotations of 8-bit bytes. Additional arguments can be used to over-ride these defaults. Any case where the number of rotations modulo the width is zero represents a rotation of all bits back to their starting positions. This implementation should handle any integer number of rotations over bitfields of any valid (positive integer) length.
 
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
' no rotations and shift aritmetic are available in QB64
' Bitwise operator in Qbasic and QB64
Line 5,068 ⟶ 5,332:
 
</syntaxhighlight>
 
=={{header|Quackery}}==
 
Integers in Quackery are bignums, so the bitwise left rotate word <code>rot64</code> rotates specifically the least significant 64 bits of an integer. There is no corresponding bitwise right rotate, but it is readily defined from <code>rot64</code>.
 
<syntaxhighlight lang=Quackery"quackery"> [ [] swap
64 times
[ 2 /mod
Line 5,108 ⟶ 5,371:
bitwise RROTATE: 1111111111111110000000000000000000000000000000000000000000011111
</pre>
 
=={{header|R}}==
 
=== Native functions in R 3.x ===
<syntaxhighlight lang="rsplus"># Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd
 
a <- 35
Line 5,126 ⟶ 5,388:
 
===Using ''as.hexmode'' or ''as.octmode''===
<syntaxhighlight lang="rsplus">a <- as.hexmode(35)
b <- as.hexmode(42)
as.integer(a & b) # 34
Line 5,134 ⟶ 5,396:
===Using ''intToBits''===
The logical operators in R, namely &, | and !, are designed to work on logical vectors rather than bits. It is possible to convert from integer to logical vector and back to make these work as required, e.g.
<syntaxhighlight lang="rsplus">intToLogicalBits <- function(intx) as.logical(intToBits(intx))
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb]))
"%AND%" <- function(x, y)
Line 5,149 ⟶ 5,411:
 
===Using ''bitops'' package===
<syntaxhighlight lang="rsplus">library(bitops)
bitAnd(35, 42) # 34
bitOr(35, 42) # 43
Line 5,157 ⟶ 5,419:
bitShiftR(35, 1) # 17
# Note that no bit rotation is provided in this package</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define a 255)
Line 5,174 ⟶ 5,435:
'(5 255 250 -256 8160 7)
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2017.05}}
<syntaxhighlight lang="raku" line>constant MAXINT = uint.Range.max;
constant BITS = MAXINT.base(2).chars;
 
Line 5,230 ⟶ 5,490:
-65432 shift left 31: 1111111111111111100000000011010000000000000000000000000000000000
-65432 rotate left 31: 1111111111111111100000000011010001111111111111111111111111111111</pre>
 
=={{header|Red}}==
<syntaxhighlight lang="red">Red [Source: https://github.com/vazub/rosetta-red]
 
a: 10
Line 5,262 ⟶ 5,521:
a << b: 40
</pre>
 
=={{header|Retro}}==
There is no predefined arithmetic shifts in Retro.
 
<syntaxhighlight lang=Retro"retro">
: bitwise ( ab- )
cr
Line 5,278 ⟶ 5,536:
2over >> "a >> b = %d\n" puts
2drop ;</syntaxhighlight>
 
=={{header|REXX}}==
<pre>
Line 5,290 ⟶ 5,547:
╚═══════════════════════════════════════════════════════════════════════════════════════╝
</pre>
<syntaxhighlight lang="rexx">/*REXX program performs bit─wise operations on integers: & | && ¬ «L »R */
numeric digits 1000 /*be able to handle ginormous integers.*/
say center('decimal', 9) center("value", 9) center('bits', 50)
Line 5,326 ⟶ 5,583:
2 A [»B] 10
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
x = 8
y = 2
Line 5,339 ⟶ 5,595:
see "x >> y - Binary Right Shift : " + (x >> y) + nl
</syntaxhighlight>
 
=={{header|RLaB}}==
 
Line 5,345 ⟶ 5,600:
are integers then the result of the operation is an integer as well.
 
<syntaxhighlight lang=RLaB"rlab">>> x = int(3);
>> y = int(1);
>> z = x && y; printf("0x%08x\n",z); // logical 'and'
Line 5,358 ⟶ 5,613:
>> z = x / i2; printf("0x%08x\n",z); // right-shift is division by 2 where both arguments are integers
0x00000001</syntaxhighlight>
 
=={{header|Robotic}}==
<syntaxhighlight lang="robotic">
input string "First value"
set "local1" to "input"
Line 5,377 ⟶ 5,631:
. "Bitwise rotation is not natively supported"
</syntaxhighlight>
=={{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}}==
<syntaxhighlight lang="ruby">def bitwise(a, b)
form = "%1$7s:%2$6d %2$016b"
puts form % ["a", a]
Line 5,406 ⟶ 5,681:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
let a: u8 = 105;
let b: u8 = 91;
Line 5,431 ⟶ 5,706:
a >> 3 = 00001101
</pre>
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">/* rotations are not available, but are easy to implement with the other bitwise operators */
data _null_;
a=105;
Line 5,445 ⟶ 5,719:
put _all_;
run;</syntaxhighlight>
 
=={{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}}==
 
<syntaxhighlight lang="scala">def bitwise(a: Int, b: Int) {
println("a and b: " + (a & b))
println("a or b: " + (a | b))
Line 5,462 ⟶ 5,761:
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^6</math>RS}}
<syntaxhighlight lang="scheme">(import (rnrs arithmetic bitwise (6)))
 
(define (bitwise a b)
Line 5,478 ⟶ 5,777:
(bitwise 255 5)</syntaxhighlight>
Output:
<syntaxhighlight lang="text">5
255
250
Line 5,485 ⟶ 5,784:
 
''Note: bitwise operations were also described in [http://srfi.schemers.org/srfi-60/ SRFI-60], with additional aliases (and previously discussed in [http://srfi.schemers.org/srfi-33/ SRFI-33] which remained draft).''
 
=={{header|Seed7}}==
The type [http://seed7.sourceforge.net/manual/types.htm#integer integer] is intended for arithmetic operations.
Line 5,494 ⟶ 5,792:
Right shifting of bin32 values is done with logical shifts.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bin32.s7i";
 
Line 5,542 ⟶ 5,840:
a rolR b: 11010000000000000000001111111000
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func bitwise(a, b) {
say ('a and b : ', a & b)
say ('a or b : ', a | b)
Line 5,563 ⟶ 5,860:
a >> b : 1
</pre>
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
COMMENT TO MY KNOWLEDGE SIMULA DOES NOT SUPPORT BITWISE OPERATIONS SO WE MUST WRITE PROCEDURES FOR THE JOB ;
INTEGER WORDSIZE;
Line 5,678 ⟶ 5,974:
A ROTR B : -1073741823
</pre>
 
=={{header|Slate}}==
<syntaxhighlight lang="slate">[ |:a :b |
 
inform: (a bitAnd: b) printString.
Line 5,691 ⟶ 5,986:
] applyTo: {8. 12}.</syntaxhighlight>
'''Bold text'''
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
Line 5,697 ⟶ 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.
<syntaxhighlight lang="smalltalk">| testBitFunc |
testBitFunc := [ :a :b |
('%1 and %2 is %3' % { a. b. (a bitAnd: b) }) displayNl.
Line 5,710 ⟶ 6,004:
in addition to the above,
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">(a bitClear: b) "mask out bits"
(a bitAt: index) "retrieve a bit (bit-index, one-based)"
(a setBit: index) "set a bit (bit-index)"
Line 5,720 ⟶ 6,014:
 
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:
<syntaxhighlight lang="sml">fun bitwise_ints (a, b) = (
print ("a and b: " ^ IntInf.toString (IntInf.andb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n");
print ("a or b: " ^ IntInf.toString (IntInf.orb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n");
Line 5,732 ⟶ 6,061:
)</syntaxhighlight>
More shifts are available for words (unsigned ints):
<syntaxhighlight lang="sml">fun bitwise_words (a, b) = (
print ("a and b: " ^ Word.fmt StringCvt.DEC (Word.andb (a, b)) ^ "\n");
print ("a or b: " ^ Word.fmt StringCvt.DEC (Word.orb (a, b)) ^ "\n");
Line 5,744 ⟶ 6,073:
=={{header|Stata}}==
Stata does not have bitwise operators as of version 15.1. It's possible to use Mata functions '''[https://www.stata.com/help.cgi?mf_inbase inbase]''' and '''frombase''' to convert integers to binary strings, and operate on these, but it will be much slower than native operators. William Matsuoka has written functions for this [http://www.wmatsuoka.com/stata/building-an-api-library here].
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">func bitwise(a: Int, b: Int) {
// All bitwise operations (including shifts)
// require both operands to be the same type
Line 5,771 ⟶ 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:
<syntaxhighlight lang=SystemVerilog"systemverilog">program main;
 
initial begin
Line 5,797 ⟶ 6,124:
If we want to do a variable bit rotation, then we need to think in hardware terms, and build a mux structure (this could be a function, but using a module allows it to be parameterized:
 
<syntaxhighlight lang=SystemVerilog"systemverilog">module rotate(in, out, shift);
 
parameter BITS = 32;
Line 5,811 ⟶ 6,138:
 
of course, one could always write the foreach loop inline.
 
=={{header|Tailspin}}==
Bytes values are infinitely extended to the left by sign extension when needed. The shift message can be used for all types of shifts, depending on the fill pattern which is infinitely repeated as needed to supply bits for vacated positions.
<syntaxhighlight lang="tailspin">
def a: [x f075 x];
def b: [x 81 x];
Line 5,840 ⟶ 6,166:
f075 rotated right 3 bits is be0e
</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">proc bitwise {a b} {
puts [format "a and b: %#08x" [expr {$a & $b}]]
puts [format "a or b: %#08x" [expr {$a | $b}]]
Line 5,851 ⟶ 6,176:
}</syntaxhighlight>
There are no built-in operations for arithmetic right shift or for bit rotation. Indeed, rotation precludes the use of arbitrary-width integers and can only be defined with respect to a particular width. However, we can simulate these operations for 32-bit values (requires Tcl 8.5):
<syntaxhighlight lang="tcl">proc bitwiseUnsupported {a b} {
set bits 0xFFFFFFFF
# Force interpretation as a 32-bit unsigned value
Line 5,864 ⟶ 6,189:
}]]
}</syntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
Line 5,871 ⟶ 6,195:
The right shift operation fills the new leftmost bit with a copy of the old leftmost bit.
 
<syntaxhighlight lang="ti89b">bitwise(a,b)
Prgm
Local show, oldbase
Line 5,894 ⟶ 6,218:
setMode("Base",oldbase)
EndPrgm</syntaxhighlight>
=={{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}}==
<syntaxhighlight lang=Vala"vala">void testbit(int a, int b) {
print(@"input: a = $a, b = $b\n");
print(@"AND: $a & $b = $(a & b)\n");
Line 5,922 ⟶ 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").
 
<syntaxhighlight lang="vb">Debug.Print Hex(&HF0F0 And &HFF00) 'F000
Debug.Print Hex(&HF0F0 Or &HFF00) 'FFF0
Debug.Print Hex(&HF0F0 Xor &HFF00) 'FF0
Line 5,936 ⟶ 6,340:
The other operations in the task are not builtin, but are easy to implement. Integers are signed, and overflow throws and exception, one must take care of this.
 
<syntaxhighlight lang="vb">Function MaskL(k As Integer) As Long
If k < 1 Then
MaskL = 0
Line 6,018 ⟶ 6,422:
Examples
 
<syntaxhighlight lang="vb">Debug.Print Hex(MaskL(8)) 'FF000000
Debug.Print Hex(MaskR(8)) 'FF
Debug.Print Hex(Bit(7)) '80
Line 6,030 ⟶ 6,434:
Debug.Print Hex(RotateR(65535, -8)) 'FFFF00
</syntaxhighlight>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
identical syntax as in [[#VBA]].
 
=={{header|Visual Basic .NET}}==
<syntaxhighlight lang="vbnet">Sub Test(a as Integer, b as Integer)
WriteLine("And " & a And b)
WriteLine("Or " & a Or b)
Line 6,046 ⟶ 6,448:
 
Visual Basic doesn't have built-in support for bitwise rotation.
 
=={{header|Wren}}==
In Wren all numbers are represented in 64-bit floating point form.
Line 6,055 ⟶ 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.
<syntaxhighlight lang=ecmascript"wren">var rl = Fn.new { |x, y| x << y | x >> (32-y) }
 
var rr = Fn.new { |x, y| x >> y | x << (32-y) }
Line 6,094 ⟶ 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)
<syntaxhighlight lang="asm"> extern printf
global main
Line 6,198 ⟶ 6,599:
 
end</syntaxhighlight>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "bitwise"
 
Line 6,268 ⟶ 6,668:
10101 Rotr 11: 10100000000000000000000000000010
</pre>
 
=={{header|XLISP}}==
<syntaxhighlight lang="lisp">(defun bitwise-operations (a b)
; rotate operations are not supported
(print `(,a and ,b = ,(logand a b)))
Line 6,278 ⟶ 6,677:
(print `(,a right shift by ,b = ,(lsh a (- b)))) ; negative second operand shifts right
(print `(,a arithmetic right shift by ,b = ,(ash a (- b)))) )</syntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">Text(0, "A and B = "); HexOut(0, A and B); CrLf(0); \alternate symbol: &
Text(0, "A or B = "); HexOut(0, A or B); CrLf(0); \alternate symbol: !
Text(0, "A xor B = "); HexOut(0, A xor B); CrLf(0); \alternate symbol: |
Line 6,296 ⟶ 6,694:
operator was introduced at a time when only uppercase characters were
available (such as on the Apple II). The XOR operator was added later.
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">sub formBin$(n)
return right$("00000000" + bin$(n), 8)
end sub
Line 6,317 ⟶ 6,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>
 
Line 6,351 ⟶ 6,747:
* <code>RLC/RRC</code> copies the bit "pushed out" to the carry but the old carry isn't rotated in.
 
<syntaxhighlight lang="z80">LD A,&05
RLA
 
Line 6,362 ⟶ 6,758:
LD A,&05
RRCA</syntaxhighlight>
 
 
 
=={{header|zkl}}==
No bitwise rotates. Shifts are unsigned.
<syntaxhighlight lang="zkl">(7).bitAnd(1) //-->1
(8).bitOr(1) //-->9
(7).bitXor(1) //-->6
Line 6,375 ⟶ 6,768:
(-1).toString(16) //-->ffffffffffffffff
(-1).shiftRight(1).toString(16) //-->7fffffffffffffff</syntaxhighlight>
 
 
{{omit from|bc|No built-in bitwise operations}}
{{omit from|dc|No built-in bitwise operations}}
2,442

edits