Bitwise operations: Difference between revisions

m
 
(175 intermediate revisions by 73 users not shown)
Line 1:
{{task|Discrete math}}
{{task|Discrete math}}{{basic data operation}}Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
{{basic data operation}}
 
;Task:
Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.
 
All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.
 
If any operation is not available in your language, note it.
<br><br>
=={{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))
print(‘x XOR y = ’(x (+) y))
print(‘x SHL y = ’(x << y))
print(‘x SHR y = ’(x >> y))
print(‘x ROL y = ’rotl(x, y))
print(‘x ROR y = ’rotr(x, y))</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 = -2147483646
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Bitwise operations 15/02/2017
BITWISE CSECT
USING BITWISE,R13
B 72(R15)
DC 17F'0'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
L R1,A
XDECO R1,PG
MVC OP,=CL7'A='
XPRNT OP,L'OP+L'PG
L R1,B
XDECO R1,PG
MVC OP,=CL7'B='
XPRNT OP,L'OP+L'PG
* And
L R1,A
N R1,B
XDECO R1,PG
MVC OP,=C'A AND B'
XPRNT OP,L'OP+L'PG
* Or
L R1,A
O R1,B
XDECO R1,PG
MVC OP,=C'A OR B'
XPRNT OP,L'OP+L'PG
* Xor
L R1,A
X R1,B
XDECO R1,PG
MVC OP,=C'A XOR B'
XPRNT OP,L'OP+L'PG
* Not
L R1,A
X R1,=X'FFFFFFFF' not (by xor -1)
XDECO R1,PG
MVC OP,=CL7'NOT A'
XPRNT OP,L'OP+L'PG
*
MVC A,=X'80000008' a=-2147483640 (-2^31+8)
L R1,A
XDECO R1,PG
MVC OP,=CL7'A='
XPRNT OP,L'OP+L'PG
* shift right arithmetic (on 31 bits)
L R1,A
SRA R1,3
XDECO R1,PG
MVC OP,=C'A SRA 3'
XPRNT OP,L'OP+L'PG
* shift left arithmetic (on 31 bits)
L R1,A
SLA R1,3
XDECO R1,PG
MVC OP,=C'A SLA 3'
XPRNT OP,L'OP+L'PG
* shift right logical (on 32 bits)
L R1,A
SRL R1,3
XDECO R1,PG
MVC OP,=C'A SRL 3'
XPRNT OP,L'OP+L'PG
* shift left logical (on 32 bits)
L R1,A
SLL R1,3
XDECO R1,PG
MVC OP,=C'A SLL 3'
XPRNT OP,L'OP+L'PG
*
RETURN L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
A DC F'21'
B DC F'3'
OP DS CL7
PG DS CL12
YREGS
END BITWISE</syntaxhighlight>
{{out}}
<pre>
A= 21
B= 3
A AND B 1
A OR B 23
A XOR B 22
NOT A -22
A= -2147483640
A SRA 3 -268435455
A SLA 3 -2147483584
A SRL 3 268435457
A SLL 3 64
</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 #.)
 
<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
SEC ;if the value in A is negative, setting the carry will ensure that ROR will insert a 1 into bit 7 of A upon rotating.
SKIP:
ROR</syntaxhighlight>
 
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|8051 Assembly}}==
Integer one is assumed to be a, integer two assumed to be b.
Line 6 ⟶ 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 57 ⟶ 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">
report z_bitwise_operations.
 
class hex_converter definition.
public section.
class-methods:
to_binary
importing
hex_value type x
returning
value(binary_value) type string,
 
to_decimal
importing
hex_value type x
returning
value(decimal_value) type int4.
endclass.
 
 
class hex_converter implementation.
method to_binary.
data(number_of_bits) = xstrlen( hex_value ) * 8.
 
do number_of_bits times.
get bit sy-index of hex_value into data(bit).
 
binary_value = |{ binary_value }{ bit }|.
enddo.
endmethod.
 
 
method to_decimal.
decimal_value = hex_value.
endmethod.
endclass.
 
 
class missing_bitwise_operations definition.
public section.
class-methods:
arithmetic_shift_left
importing
old_value type x
change_with type x
exporting
new_value type x,
 
arithmetic_shift_right
importing
old_value type x
change_with type x
exporting
new_value type x,
 
logical_shift_left
importing
old_value type x
change_with type x
exporting
new_value type x,
 
logical_shift_right
importing
old_value type x
change_with type x
exporting
new_value type x,
 
rotate_left
importing
old_value type x
change_with type x
exporting
new_value type x,
 
rotate_right
importing
old_value type x
change_with type x
exporting
new_value type x.
endclass.
 
 
class missing_bitwise_operations implementation.
method arithmetic_shift_left.
clear new_value.
 
new_value = old_value * 2 ** change_with.
endmethod.
 
 
method arithmetic_shift_right.
clear new_value.
 
new_value = old_value div 2 ** change_with.
endmethod.
 
 
method logical_shift_left.
clear new_value.
 
data(bits) = hex_converter=>to_binary( old_value ).
 
data(length_of_bit_sequence) = strlen( bits ).
 
bits = shift_left(
val = bits
places = change_with ).
 
while strlen( bits ) < length_of_bit_sequence.
bits = |{ bits }0|.
endwhile.
 
do strlen( bits ) times.
data(index) = sy-index - 1.
 
data(current_bit) = bits+index(1).
 
if current_bit eq `1`.
set bit sy-index of new_value.
endif.
enddo.
endmethod.
 
 
method logical_shift_right.
clear new_value.
 
data(bits) = hex_converter=>to_binary( old_value ).
 
data(length_of_bit_sequence) = strlen( bits ).
 
bits = shift_right(
val = bits
places = change_with ).
 
while strlen( bits ) < length_of_bit_sequence.
bits = |0{ bits }|.
endwhile.
 
do strlen( bits ) times.
data(index) = sy-index - 1.
 
data(current_bit) = bits+index(1).
 
if current_bit eq `1`.
set bit sy-index of new_value.
endif.
enddo.
endmethod.
 
 
method rotate_left.
clear new_value.
 
data(bits) = hex_converter=>to_binary( old_value ).
 
bits = shift_left(
val = bits
circular = change_with ).
 
do strlen( bits ) times.
data(index) = sy-index - 1.
 
data(current_bit) = bits+index(1).
 
if current_bit eq `1`.
set bit sy-index of new_value.
endif.
enddo.
endmethod.
 
 
method rotate_right.
clear new_value.
 
data(bits) = hex_converter=>to_binary( old_value ).
 
bits = shift_right(
val = bits
circular = change_with ).
 
do strlen( bits ) times.
data(index) = sy-index - 1.
 
data(current_bit) = bits+index(1).
 
if current_bit eq `1`.
set bit sy-index of new_value.
endif.
enddo.
endmethod.
endclass.
 
 
start-of-selection.
data:
a type x length 4 value 255,
b type x length 4 value 2,
result type x length 4.
 
write: |a -> { a }, { hex_converter=>to_binary( a ) }, { hex_converter=>to_decimal( a ) }|, /.
 
write: |b -> { b }, { hex_converter=>to_binary( b ) }, { hex_converter=>to_decimal( b ) }|, /.
 
result = a bit-and b.
write: |a & b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
result = a bit-or b.
write: |a \| b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
result = a bit-xor b.
write: |a ^ b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
result = bit-not a.
write: |~a -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
missing_bitwise_operations=>arithmetic_shift_left(
exporting
old_value = bit-not a
change_with = b
importing
new_value = result ).
write: |~a << b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
missing_bitwise_operations=>arithmetic_shift_right(
exporting
old_value = bit-not a
change_with = b
importing
new_value = result ).
write: |~a >> b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
missing_bitwise_operations=>logical_shift_left(
exporting
old_value = a
change_with = b
importing
new_value = result ).
write: |a <<< b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
missing_bitwise_operations=>logical_shift_right(
exporting
old_value = bit-not a
change_with = b
importing
new_value = result ).
write: |~a >>> b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
missing_bitwise_operations=>rotate_left(
exporting
old_value = bit-not a
change_with = b
importing
new_value = result ).
write: |~a rotl b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
 
missing_bitwise_operations=>rotate_right(
exporting
old_value = a
change_with = b
importing
new_value = result ).
write: |a rotr b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /.
</syntaxhighlight>
 
{{output}}
<pre>
a -> 000000FF, 00000000000000000000000011111111, 255
 
b -> 00000002, 00000000000000000000000000000010, 2
 
a & b -> 00000002, 00000000000000000000000000000010, 2
 
a | b -> 000000FF, 00000000000000000000000011111111, 255
 
a ^ b -> 000000FD, 00000000000000000000000011111101, 253
 
~a -> FFFFFF00, 11111111111111111111111100000000, -256
 
~a << b -> FFFFFC00, 11111111111111111111110000000000, -1024
 
~a >> b -> FFFFFFC0, 11111111111111111111111111000000, -64
 
a <<< b -> 000003FC, 00000000000000000000001111111100, 1020
 
~a >>> b -> 3FFFFFC0, 00111111111111111111111111000000, 1073741760
 
~a rotl b -> FFFFFC03, 11111111111111111111110000000011, -1021
 
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 67 ⟶ 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 80 ⟶ 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.
 
<syntaxhighlight lang ="ada">with Ada.Text_Io;Text_IO, use Ada.Text_IoInterfaces;
withuse Interfaces; useAda.Text_IO, Interfaces;
procedure Bitwise is
subtype Byte is Unsigned_8;
package Byte_Io is new Ada.Text_Io.Modular_Io(Byte);
A : Byte := 255;
B : Byte := 170;
X : Byte := 128;
N : Natural := 1;
 
procedure Bitwise is
begin
subtype Byte is Unsigned_8;
Put_Line("A and B = "); Byte_Io.Put(Item => A and B, Base => 2);
package Byte_IO is new Ada.Text_Io.Modular_IO (Byte);
Put_Line("A or B = "); Byte_IO.Put(Item => A or B, Base => 2);
Put_Line("A xor B = "); Byte_Io.Put(Item => A xor B, Base => 2);
Put_Line("Not A = "); Byte_IO.Put(Item => not A, Base => 2);
New_Line(2);
Put_Line(Unsigned_8'Image(Shift_Left(X, N))); -- Left shift
Put_Line(Unsigned_8'Image(Shift_Right(X, N))); -- Right shift
Put_Line(Unsigned_8'Image(Shift_Right_Arithmetic(X, N))); -- Right Shift Arithmetic
Put_Line(Unsigned_8'Image(Rotate_Left(X, N))); -- Left rotate
Put_Line(Unsigned_8'Image(Rotate_Right(X, N))); -- Right rotate
end bitwise;</lang>
 
A : constant Byte := 2#00011110#;
B : constant Byte := 2#11110100#;
X : constant Byte := 128;
N : constant Natural := 1;
begin
Put ("A and B = "); Byte_IO.Put (Item => A and B, Base => 2); New_Line;
Put ("A or B = "); Byte_IO.Put (Item => A or B, Base => 2); New_Line;
Put ("A xor B = "); Byte_IO.Put (Item => A xor B, Base => 2); New_Line;
Put ("not A = "); Byte_IO.Put (Item => not A, Base => 2); New_Line;
New_Line (2);
Put_Line (Unsigned_8'Image (Shift_Left (X, N)));
Put_Line (Unsigned_8'Image (Shift_Right (X, N)));
Put_Line (Unsigned_8'Image (Shift_Right_Arithmetic (X, N)));
Put_Line (Unsigned_8'Image (Rotate_Left (X, N)));
Put_Line (Unsigned_8'Image (Rotate_Right (X, N)));
end Bitwise;</syntaxhighlight>
=={{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 122 ⟶ 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 131 ⟶ 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 194 ⟶ 974:
bitwise(16rff,16raa,5)
END CO
)</langsyntaxhighlight>
Output:
<pre> bits shorths: +1 1 plus the number of extra SHORT BITS types
Line 220 ⟶ 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 232 ⟶ 1,012:
i := ABS j;
 
printf(($g", 8r"8r4d", "8(g)l$, i, j, k[bits width-8+1:]))</langsyntaxhighlight>
Output:
<pre>
Line 238 ⟶ 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 ) ;
begin
bits b1, b2;
% the Algol W bitwse operations operate on bits values, so we first convert the %
% integers to bits values using the builtin bitstring procedure %
% the results are converted back to integers using the builtin number procedure %
% all Algol W bits and integers are 32 bits quantities %
b1 := bitstring( n1 );
b2 := bitstring( n2 );
% perform the operaations and display the results as integers %
write( n1, " and ", n2, " = ", number( b1 and b2 ) );
write( n1, " or ", n2, " = ", number( b1 or b2 ) );
write( " "
, " not ", n1, " = ", number( not b1 ) );
write( n1, " shl ", n2, " = ", number( b1 shl n2 ), " ( left-shift )" );
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" )
end bitOPerations ;</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.
 
If we really do need to use Applescript for bitwise operations, two immediate possibilities come to mind:
 
* We can use JavaScript operators through an ObjC bridge to JavaScript for Automation, or
* we can write our own functions – converting between 32-bit signed integers and corresponding lists of booleans, and performing the bitwise operations on the boolean lists before converting back to integers.
 
 
'''First option''' – 'dialling out to JavaScript for Automation':
 
This is feasible, (see below) subject to the limitations that:
 
* Javascript lacks bit rotation operators, and
* in the case of the JS left shift operator '''(<<)''' the right operand needs to be masked with '''0x1F''' (31), which is its maximum effective value.
 
 
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
 
-- BIT OPERATIONS FOR APPLESCRIPT (VIA JAVASCRIPT FOR AUTOMATION)
 
-- bitAND :: Int -> Int -> Int
on bitAND(x, y)
jsOp2("&", x, y)
end bitAND
 
-- bitOR :: Int -> Int -> Int
on bitOR(x, y)
jsOp2("|", x, y)
end bitOR
 
-- bitXOr :: Int -> Int -> Int
on bitXOR(x, y)
jsOp2("^", x, y)
end bitXOR
 
-- bitNOT :: Int -> Int
on bitNOT(x)
jsOp1("~", x)
end bitNOT
 
-- (<<) :: Int -> Int -> Int
on |<<|(x, y)
if 31 < y then
0
else
jsOp2("<<", x, y)
end if
end |<<|
 
-- Logical right shift
-- (>>>) :: Int -> Int -> Int
on |>>>|(x, y)
jsOp2(">>>", x, y)
end |>>>|
 
-- Arithmetic right shift
-- (>>) :: Int -> Int -> Int
on |>>|(x, y)
jsOp2(">>", x, y)
end |>>|
 
 
-- TEST ----------------------------------------------------------
on run
-- Using an ObjC interface to Javascript for Automation
set strClip to bitWise(255, 170)
set the clipboard to strClip
strClip
end run
 
-- bitWise :: Int -> Int -> String
on bitWise(a, b)
set labels to {"a AND b", "a OR b", "a XOR b", "NOT a", ¬
"a << b", "a >>> b", "a >> b"}
set xs to {bitAND(a, b), bitOR(a, b), bitXOR(a, b), bitNOT(a), ¬
|<<|(a, b), |>>>|(a, b), |>>|(a, b)}
script asBin
property arrow : " -> "
on |λ|(x, y)
justifyRight(8, space, x) & arrow & ¬
justifyRight(14, space, y as text) & arrow & showBinary(y)
end |λ|
end script
unlines({"32 bit signed integers (in two's complement binary encoding)", "", ¬
unlines(zipWith(asBin, ¬
{"a = " & a as text, "b = " & b as text}, {a, b})), "", ¬
unlines(zipWith(asBin, labels, xs))})
end bitWise
 
-- CONVERSIONS AND DISPLAY
 
-- bitsFromInt :: Int -> Either String [Bool]
on bitsFromIntLR(x)
script go
on |λ|(n, d, bools)
set xs to {0 ≠ d} & bools
if n > 0 then
|λ|(n div 2, n mod 2, xs)
else
xs
end if
end |λ|
end script
set a to abs(x)
if (2.147483647E+9) < a then
|Left|("Integer overflow – maximum is (2 ^ 31) - 1")
else
set bs to go's |λ|(a div 2, a mod 2, {})
if 0 > x then
|Right|(replicate(32 - (length of bs), true) & ¬
binSucc(map(my |not|, bs)))
else
set bs to go's |λ|(a div 2, a mod 2, {})
|Right|(replicate(32 - (length of bs), false) & bs)
end if
end if
end bitsFromIntLR
 
-- Successor function (+1) for unsigned binary integer
 
-- binSucc :: [Bool] -> [Bool]
on binSucc(bs)
script succ
on |λ|(a, x)
if a then
if x then
Tuple(a, false)
else
Tuple(x, true)
end if
else
Tuple(a, x)
end if
end |λ|
end script
set tpl to mapAccumR(succ, true, bs)
if |1| of tpl then
{true} & |2| of tpl
else
|2| of tpl
end if
end binSucc
 
-- showBinary :: Int -> String
on showBinary(x)
script showBin
on |λ|(xs)
script bChar
on |λ|(b)
if b then
"1"
else
"0"
end if
end |λ|
end script
map(bChar, xs)
end |λ|
end script
bindLR(my bitsFromIntLR(x), showBin)
end showBinary
 
 
-- JXA ------------------------------------------------------------------
 
--jsOp2 :: String -> a -> b -> c
on jsOp2(strOp, a, b)
bindLR(evalJSLR(unwords({a as text, strOp, b as text})), my |id|) as integer
end jsOp2
 
--jsOp2 :: String -> a -> b
on jsOp1(strOp, a)
bindLR(evalJSLR(unwords({strOp, a as text})), my |id|) as integer
end jsOp1
 
-- evalJSLR :: String -> Either String a
on evalJSLR(strJS)
try -- NB if gJSC is global it must be released
-- (e.g. set to null) at end of script
gJSC's evaluateScript
on error
set gJSC to current application's JSContext's new()
log ("new JSC")
end try
set v to unwrap((gJSC's evaluateScript:(strJS))'s toObject())
if v is missing value then
|Left|("JS evaluation error")
else
|Right|(v)
end if
end evalJSLR
 
-- GENERIC FUNCTIONS --------------------------------------------------
 
-- Left :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
 
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
 
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
 
-- Absolute value.
-- abs :: Num -> Num
on abs(x)
if 0 > x then
-x
else
x
end if
end abs
 
-- bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
if missing value is not |Right| of m then
mReturn(mf)'s |λ|(|Right| of m)
else
m
end if
end bindLR
 
-- foldr :: (a -> b -> b) -> b -> [a] -> b
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
 
-- id :: a -> a
on |id|(x)
x
end |id|
 
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- 'The mapAccumR function behaves like a combination of map and foldr;
-- it applies a function to each element of a list, passing an accumulating
-- parameter from |Right| to |Left|, and returning a final value of this
-- accumulator together with the new list.' (see Hoogle)
-- mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumR(f, acc, xs)
script
on |λ|(x, a, i)
tell mReturn(f) to set pair to |λ|(|1| of a, x, i)
Tuple(|1| of pair, (|2| of pair) & |2| of a)
end |λ|
end script
foldr(result, Tuple(acc, []), xs)
end mapAccumR
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
-- not :: Bool -> Bool
on |not|(p)
not p
end |not|
 
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
 
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
 
-- unwords :: [String] -> String
on unwords(xs)
set {dlm, my text item delimiters} to {my text item delimiters, space}
set s to xs as text
set my text item delimiters to dlm
return s
end unwords
 
-- unwrap :: NSObject -> a
on unwrap(objCValue)
if objCValue is missing value then
missing value
else
set ca to current application
item 1 of ((ca's NSArray's arrayWithObject:objCValue) as list)
end if
end unwrap
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
if 1 > lng then return {}
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith</syntaxhighlight>
{{Out}}
<pre>32 bit signed integers (in two's complement binary encoding)
 
a = 255 -> 255 -> 00000000000000000000000011111111
b = 170 -> 170 -> 00000000000000000000000010101010
 
a AND b -> 170 -> 00000000000000000000000010101010
a OR b -> 255 -> 00000000000000000000000011111111
a XOR b -> 85 -> 00000000000000000000000001010101
NOT a -> -256 -> 11111111111111111111111100000000
a << b -> 0 -> 00000000000000000000000000000000
a >>> b -> 0 -> 00000000000000000000000000000000
a >> b -> 0 -> 00000000000000000000000000000000</pre>
 
 
'''Second option''' – writing our own bitwise functions for Applescript:
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
 
-- BITWISE OPERATIONS FOR APPLESCRIPT ---------------------------------------
 
-- bitAND :: Int -> Int -> Int
on bitAND(x, y)
bitOp2(my |and|, x, y)
end bitAND
 
-- bitOR :: Int -> Int -> Int
on bitOR(x, y)
bitOp2(my |or|, x, y)
end bitOR
 
-- bitXOr :: Int -> Int -> Int
on bitXOR(x, y)
bitOp2(my xor, x, y)
end bitXOR
 
-- bitNOT :: Int -> Int
on bitNOT(x)
script notBits
on |λ|(xs)
bindLR(intFromBitsLR(map(my |not|, xs)), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(x), notBits)
end bitNOT
 
-- (<<) :: Int -> Int -> Int
on |<<|(a, b)
script logicLshift
on |λ|(bs)
bindLR(intFromBitsLR(take(32, drop(b, bs) & replicate(b, false))), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), logicLshift)
end |<<|
 
-- Logical right shift
-- (>>>) :: Int -> Int -> Int
on |>>>|(a, b)
script logicRShift
on |λ|(bs)
bindLR(intFromBitsLR(take(32, replicate(b, false) & drop(b, bs))), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), logicRShift)
end |>>>|
 
-- Arithmetic right shift
-- (>>) :: Int -> Int -> Int
on |>>|(a, b)
script arithRShift
on |λ|(bs)
if 0 < length of bs then
set sign to item 1 of bs
else
set sign to false
end if
bindLR(intFromBitsLR(take(32, replicate(b, sign) & drop(b, bs))), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), arithRShift)
end |>>|
 
-- bitRotL :: Int -> Int -> Int
on bitRotL(a, b)
script lRot
on |λ|(bs)
bindLR(intFromBitsLR(rotate(-b, bs)), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), lRot)
end bitRotL
 
-- bitRotR :: Int -> Int -> Int
on bitRotR(a, b)
script rRot
on |λ|(bs)
bindLR(intFromBitsLR(rotate(b, bs)), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(a), rRot)
end bitRotR
 
-- TEST ---------------------------------------------------------------
 
-- bitWise :: Int -> Int -> String
on bitWise(a, b)
set labels to {"a AND b", "a OR b", "a XOR b", "NOT a", ¬
"a << b", "a >>> b", "a >> b", "ROTL a b", "ROTR a b"}
set xs to {bitAND(a, b), bitOR(a, b), bitXOR(a, b), bitNOT(a), ¬
|<<|(a, b), |>>>|(a, b), |>>|(a, b), bitRotL(a, b), bitRotR(a, b)}
script asBin
property arrow : " -> "
on |λ|(x, y)
justifyRight(8, space, x) & arrow & ¬
justifyRight(14, space, y as text) & arrow & showBinary(y)
end |λ|
end script
unlines({"32 bit signed integers (in two's complement binary encoding)", "", ¬
unlines(zipWith(asBin, ¬
{"a = " & a as text, "b = " & b as text}, {a, b})), "", ¬
unlines(zipWith(asBin, labels, xs))})
end bitWise
 
on run
-- Assuming 32 bit signed integers (in two's complement binary encoding)
set strClip to bitWise(255, 170)
set the clipboard to strClip
strClip
end run
 
-- BINARY INTEGER CONVERSIONS AND DISPLAY ------------------------------------------------------------------
 
-- bitsFromInt :: Int -> Either String [Bool]
on bitsFromIntLR(x)
script go
on |λ|(n, d, bools)
set xs to {0 ≠ d} & bools
if n > 0 then
|λ|(n div 2, n mod 2, xs)
else
xs
end if
end |λ|
end script
set a to abs(x)
if (2.147483647E+9) < a then
|Left|("Integer overflow – maximum is (2 ^ 31) - 1")
else
set bs to go's |λ|(a div 2, a mod 2, {})
if 0 > x then
|Right|(replicate(32 - (length of bs), true) & ¬
binSucc(map(my |not|, bs)))
else
set bs to go's |λ|(a div 2, a mod 2, {})
|Right|(replicate(32 - (length of bs), false) & bs)
end if
end if
end bitsFromIntLR
 
-- intFromBitsLR :: [Bool] -> Either String Int
on intFromBitsLR(xs)
script bitSum
on |λ|(x, a, i)
if x then
a + (2 ^ (31 - i))
else
a
end if
end |λ|
end script
set lngBits to length of xs
if 32 < lngBits then
|Left|("Applescript limited to signed 32 bit integers")
else if 1 > lngBits then
|Right|(0 as integer)
else
set bits to (rest of xs)
if item 1 of xs then
|Right|(0 - foldr(bitSum, 1, map(my |not|, bits)) as integer)
else
|Right|(foldr(bitSum, 0, bits) as integer)
end if
end if
end intFromBitsLR
 
-- showBinary :: Int -> String
on showBinary(x)
script showBin
on |λ|(xs)
script bChar
on |λ|(b)
if b then
"1"
else
"0"
end if
end |λ|
end script
map(bChar, xs)
end |λ|
end script
bindLR(my bitsFromIntLR(x), showBin)
end showBinary
 
-- bitOp2 :: ((Bool -> Bool -> Bool) -> Int -> Int -> Int
on bitOp2(f, x, y)
script yBits
on |λ|(bitX)
script zipOp
on |λ|(bitY)
bitZipWithLR(f, bitX, bitY)
end |λ|
end script
bindLR(bindLR(bindLR(bitsFromIntLR(y), ¬
zipOp), my intFromBitsLR), my |id|)
end |λ|
end script
bindLR(bitsFromIntLR(x), yBits)
end bitOp2
 
-- bitZipWithLR :: ((a, b) -> c ) -> [Bool] -> [Bool] -> Either String [(Bool, Bool)]
on bitZipWithLR(f, xs, ys)
set intX to length of xs
set intY to length of ys
set intMax to max(intX, intY)
if 33 > intMax then
if intX > intY then
set {bxs, bys} to {xs, ys & replicate(intX - intY, false)}
else
set {bxs, bys} to {xs & replicate(intY - intX, false), ys}
end if
tell mReturn(f)
set lst to {}
repeat with i from 1 to intMax
set end of lst to |λ|(item i of bxs, item i of bys)
end repeat
return |Right|(lst)
end tell
else
|Left|("Above maximum of 32 bits")
end if
end bitZipWithLR
 
-- Successor function (+1) for unsigned binary integer
 
-- binSucc :: [Bool] -> [Bool]
on binSucc(bs)
script succ
on |λ|(a, x)
if a then
if x then
Tuple(a, false)
else
Tuple(x, true)
end if
else
Tuple(a, x)
end if
end |λ|
end script
set tpl to mapAccumR(succ, true, bs)
if |1| of tpl then
{true} & |2| of tpl
else
|2| of tpl
end if
end binSucc
 
-- BOOLEANS ----------------------------------------------------
 
-- |or| :: Bool -> Bool -> Bool
on |or|(x, y)
x or y
end |or|
 
-- |and| :: Bool -> Bool -> Bool
on |and|(x, y)
x and y
end |and|
 
-- xor :: Bool -> Bool -> Bool
on xor(x, y)
(x or y) and not (x and y)
end xor
 
-- not :: Bool -> Bool
on |not|(p)
not p
end |not|
 
-- GENERAL ----------------------------------------------------
 
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
 
-- Left :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
 
-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
{type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple
 
-- Absolute value.
-- abs :: Num -> Num
on abs(x)
if 0 > x then
-x
else
x
end if
end abs
 
-- bindLR (>>=) :: Either a -> (a -> Either b) -> Either b
on bindLR(m, mf)
if missing value is not |Right| of m then
mReturn(mf)'s |λ|(|Right| of m)
else
m
end if
end bindLR
 
-- drop :: Int -> [a] -> [a]
-- drop :: Int -> String -> String
on drop(n, xs)
if class of xs is not string then
if n < length of xs then
items (1 + n) thru -1 of xs
else
{}
end if
else
if n < length of xs then
text (1 + n) thru -1 of xs
else
""
end if
end if
end drop
 
-- foldr :: (a -> b -> b) -> b -> [a] -> b
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
 
-- id :: a -> a
on |id|(x)
x
end |id|
 
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- 'The mapAccumR function behaves like a combination of map and foldr;
-- it applies a function to each element of a list, passing an accumulating
-- parameter from |Right| to |Left|, and returning a final value of this
-- accumulator together with the new list.' (see Hoogle)
-- mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumR(f, acc, xs)
script
on |λ|(x, a, i)
tell mReturn(f) to set pair to |λ|(|1| of a, x, i)
Tuple(|1| of pair, (|2| of pair) & |2| of a)
end |λ|
end script
foldr(result, Tuple(acc, []), xs)
end mapAccumR
 
-- max :: Ord a => a -> a -> a
on max(x, y)
if x > y then
x
else
y
end if
end max
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
 
-- rotate :: Int -> [a] -> [a]
on rotate(n, xs)
set lng to length of xs
if 0 > n then
set d to (-n) mod lng
else
set d to lng - (n mod lng)
end if
drop(d, xs) & take(d, xs)
end rotate
 
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
if class of xs is string then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
end if
end take
 
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
if 1 > lng then return {}
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith</syntaxhighlight>
{{Out}}
<pre>32 bit signed integers (in two's complement binary encoding)
 
a = 255 -> 255 -> 00000000000000000000000011111111
b = 170 -> 170 -> 00000000000000000000000010101010
 
a AND b -> 170 -> 00000000000000000000000010101010
a OR b -> 255 -> 00000000000000000000000011111111
a XOR b -> 85 -> 00000000000000000000000001010101
NOT a -> -256 -> 11111111111111111111111100000000
a << b -> 0 -> 00000000000000000000000000000000
a >>> b -> 0 -> 00000000000000000000000000000000
a >> b -> 0 -> 00000000000000000000000000000000
ROTL a b -> 261120 -> 00000000000000111111110000000000
ROTR a b -> 1.06954752E+9 -> 00111111110000000000000000000000</pre>
 
----
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.
repeat with i from 0 to registerSize - 1
tell (2 ^ i) to set out to out + (n1 div it) * (n2 div it) mod 2 * it
end repeat
return out div 1
end bitwiseAND
 
on bitwiseOR(n1, n2, registerSize)
set out to 0
-- Adding bit values plus a further 1 gives a carry of 1 if either or both values are 1, but not if they're both 0.
repeat with i from 0 to registerSize - 1
tell (2 ^ i) to set out to out + (n1 div it mod 2 + n2 div it mod 2 + 1) div 2 * it
end repeat
return out div 1
end bitwiseOR
 
on bitwiseXOR(n1, n2, registerSize)
set out to 0
-- Adding bit values gives 1 if they're different and 0 (with or without a carry) if they're both the same.
repeat with i from 0 to registerSize - 1
tell (2 ^ i) to set out to out + (n1 div it + n2 div it) mod 2 * it
end repeat
return out div 1
end bitwiseXOR
 
on bitwiseNOT(n, registerSize)
-- Subtract n from an all-1s value (ie. from 1 less than 2 ^ registerSize).
tell (2 ^ registerSize) to return (it - 1 - n mod it) div 1
end bitwiseNOT
 
on leftShift(n, shift, registerSize)
-- Multiply by 2 ^ shift and lose any bits beyond the left of the register.
return n * (2 ^ shift) mod (2 ^ registerSize) div 1
end leftShift
 
on rightShift(n, shift, registerSize)
-- Divide by 2 ^ shift and lose any bits beyond the right of the register.
return n mod (2 ^ registerSize) div (2 ^ shift)
end rightShift
 
on arithmeticRightShift(n, shift, registerSize)
set n to n mod (2 ^ registerSize)
-- If the number's positive and notionally sets the sign bit, reinterpret it as a negative.
tell (2 ^ (registerSize - 1)) to if (n ≥ it) then set n to n mod it - it
-- Right shift by the appropriate amount
set out to n div (2 ^ shift)
-- If the result for a negative is 0, change it to -1.
if ((n < 0) and (out is 0)) then set out to -1
return out
end arithmeticRightShift
 
on leftRotate(n, shift, registerSize)
-- Cut the register at the appropriate point, left shift the right side and right shift the left by the appropriate amounts.
set shift to shift mod (registerSize)
return leftShift(n, shift, registerSize) + rightShift(n, registerSize - shift, registerSize)
end leftRotate
 
on rightRotate(n, shift, registerSize)
-- As left rotate, but applying the shift amounts to the opposite sides.
set shift to shift mod registerSize
return rightShift(n, shift, registerSize) + leftShift(n, registerSize - shift, registerSize)
end rightRotate
 
bitwiseAND(92, 7, 16) --> 4
bitwiseOR(92, 7, 16) --> 95
bitwiseXOR(92, 7, 16) --> 91
bitwiseNOT(92, 16) --> 64453
bitwiseNOT(92, 8) --> 163
bitwiseNOT(92, 32) --> 4.294967203E+9
leftShift(92, 7, 16) --> 11776
leftShift(92, 7, 8) --> 0
rightShift(92, 7, 16) --> 0
arithmeticRightShift(92, 7, 16) --> 0
arithmeticRightShift(-92, 7, 16) --> -1
leftRotate(92, 7, 8) --> 46
rightRotate(92, 7, 8) --> 184
rightRotate(92, 7, 16) --> 47104</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program binarydigit.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/* Initialized data */
.data
szMessResultAnd: .asciz "Result of And : \n"
szMessResultOr: .asciz "Result of Or : \n"
szMessResultEor: .asciz "Result of Exclusif Or : \n"
szMessResultNot: .asciz "Result of Not : \n"
szMessResultLsl: .asciz "Result of left shift : \n"
szMessResultLsr: .asciz "Result of right shift : \n"
szMessResultAsr: .asciz "Result of Arithmetic right shift : \n"
szMessResultRor: .asciz "Result of rotate right : \n"
szMessResultRrx: .asciz "Result of rotate right with extend : \n"
szMessResultClear: .asciz "Result of Bit Clear : \n"
 
sMessAffBin: .ascii "Register value : "
sZoneBin: .space 36,' '
.asciz "\n"
 
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* save des 2 registres */
ldr r0,iAdrszMessResultAnd
bl affichageMess
mov r0,#5
and r0,#15
bl affichage2
ldr r0,iAdrszMessResultOr
bl affichageMess
mov r0,#5
orr r0,#15
bl affichage2
ldr r0,iAdrszMessResultEor
bl affichageMess
mov r0,#5
eor r0,#15
bl affichage2
ldr r0,iAdrszMessResultNot
bl affichageMess
mov r0,#5
mvn r0,r0
bl affichage2
ldr r0,iAdrszMessResultLsl
bl affichageMess
mov r0,#5
lsl r0,#1
bl affichage2
ldr r0,iAdrszMessResultLsr
bl affichageMess
mov r0,#5
lsr r0,#1
bl affichage2
ldr r0,iAdrszMessResultAsr
bl affichageMess
mov r0,#-5
bl affichage2
mov r0,#-5
asr r0,#1
bl affichage2
ldr r0,iAdrszMessResultRor
bl affichageMess
mov r0,#5
ror r0,#1
bl affichage2
ldr r0,iAdrszMessResultRrx
bl affichageMess
mov r0,#5
mov r1,#15
rrx r0,r1
bl affichage2
ldr r0,iAdrszMessResultClear
bl affichageMess
mov r0,#5
bic r0,#0b100 @ clear 3ieme bit
bl affichage2
bic r0,#4 @ clear 3ieme bit ( 4 = 100 binary)
bl affichage2
 
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszMessResultAnd: .int szMessResultAnd
iAdrszMessResultOr: .int szMessResultOr
iAdrszMessResultEor: .int szMessResultEor
iAdrszMessResultNot: .int szMessResultNot
iAdrszMessResultLsl: .int szMessResultLsl
iAdrszMessResultLsr: .int szMessResultLsr
iAdrszMessResultAsr: .int szMessResultAsr
iAdrszMessResultRor: .int szMessResultRor
iAdrszMessResultRrx: .int szMessResultRrx
iAdrszMessResultClear: .int szMessResultClear
/******************************************************************/
/* register display in binary */
/******************************************************************/
/* r0 contains the register */
affichage2:
push {r0,lr} /* save registers */
push {r1-r5} /* save others registers */
mrs r5,cpsr /* saves state register in r5 */
ldr r1,iAdrsZoneBin
mov r2,#0 @ read bit position counter
mov r3,#0 @ position counter of the written character
1: @ loop
lsls r0,#1 @ left shift with flags
movcc r4,#48 @ flag carry off character '0'
movcs r4,#49 @ flag carry on character '1'
strb r4,[r1,r3] @ character -> display zone
add r2,r2,#1 @ + 1 read bit position counter
add r3,r3,#1 @ + 1 position counter of the written character
cmp r2,#8 @ 8 bits read
addeq r3,r3,#1 @ + 1 position counter of the written character
cmp r2,#16 @ etc
addeq r3,r3,#1
cmp r2,#24
addeq r3,r3,#1
cmp r2,#31 @ 32 bits shifted ?
ble 1b @ no -> loop
 
ldr r0,iAdrsZoneMessBin @ address of message result
bl affichageMess @ display result
100:
msr cpsr,r5 /*restaur state register */
pop {r1-r5} /* restaur others registers */
pop {r0,lr}
bx lr
iAdrsZoneBin: .int sZoneBin
iAdrsZoneMessBin: .int sMessAffBin
 
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registres */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system write */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registres */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
 
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">a: 255
b: 2
 
print [a "AND" b "=" and a b]
print [a "OR" b "=" or a b]
print [a "XOR" b "=" xor a b]
print ["NOT" a "=" not a]
print [a "SHL" b "=" shl a b]
print [a "SHR" b "=" shr a b]</syntaxhighlight>
{{out}}
 
<pre>255 AND 2 = 2
255 OR 2 = 255
255 XOR 2 = 253
NOT 255 = -256
255 SHL 2 = 1020
255 SHR 2 = 63 </pre>
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">bitwise(3, 4)
bitwise(a, b)
{
Line 249 ⟶ 2,209:
MsgBox % "a << b: " . a << b ; left shift
MsgBox % "a >> b: " . a >> b ; arithmetic right shift
}</langsyntaxhighlight>
=={{header|AutoIt}}==
No arithmetic shift.
<syntaxhighlight lang="autoit">bitwise(255, 5)
Func bitwise($a, $b)
MsgBox(1, '', _
$a & " AND " & $b & ": " & BitAND($a, $b) & @CRLF & _
$a & " OR " & $b & ": " & BitOR($a, $b) & @CRLF & _
$a & " XOR " & $b & ": " & BitXOR($a, $b) & @CRLF & _
"NOT " & $a & ": " & BitNOT($a) & @CRLF & _
$a & " SHL " & $b & ": " & BitShift($a, $b * -1) & @CRLF & _
$a & " SHR " & $b & ": " & BitShift($a, $b) & @CRLF & _
$a & " ROL " & $b & ": " & BitRotate($a, $b) & @CRLF & _
$a & " ROR " & $b & ": " & BitRotate($a, $b * -1) & @CRLF )
EndFunc</syntaxhighlight>
{{out}}
 
<pre>255 AND 5: 5
255 OR 5: 255
255 XOR 5: 250
NOT 255: -256
255 SHL 5: 8160
255 SHR 5: 7
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 256 ⟶ 2,240:
{{works with|gawk}}
 
<langsyntaxhighlight lang="awk">BEGIN {
n = 11
p = 1
Line 265 ⟶ 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 278 ⟶ 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.
<lang babel>((main { (5 9) foo ! })
 
<syntaxhighlight lang="babel">({5 9}) ({cand} {cor} {cnor} {cxor} {cxnor} {shl} {shr} {ashr} {rol}) cart ! {give <- cp -> compose !} over ! {eval} over ! {;} each</syntaxhighlight>
(foo {
({cand} {cor} {cnor} {cxor} {cxnor} {cushl} {cushr} {cashr} {curol} {curor})
{ <- dup give ->
eval
%x nl <<}
each
give zap
cnot %x nl <<}))</lang>
 
{{Out}}
This program produces the following output:
<pre>[val 0x1 ]
[val 0xd ]
[val 0xfffffff7 ]
[val 0xc ]
[val 0xfffffff3 ]
[val 0xa00 ]
[val 0x0 ]
[val 0x0 ]
[val 0xa00 ]</pre>
 
The cnot operator works on just one operand:
<lang babel>1
 
d
<syntaxhighlight lang="babel">9 cnot ;</syntaxhighlight>
fffffff7
c
fffffff3
a00
0
0
a00
2800000
fffffffa</lang>
 
{{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 332 ⟶ 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.
 
<syntaxhighlight 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</syntaxhighlight>
{{in}}
<pre>A=? 2
B=? 6</pre>
{{out}}
<pre>A AND B = 2
A OR B = 6
A XOR B = 4
NOT A =-3
</pre>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 LET A=10:LET B=12
110 PRINT A;"and";B;"=";A AND B
120 PRINT A;"band";B;"=";A BAND B
130 PRINT A;"or ";B;"=";A OR B
140 PRINT A;"bor";B;"=";A BOR B
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)</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
ZX81 BASIC has no integer type (a major lacuna) and consequently no bitwise operations; but the CPU has them, so we can use a tiny machine code routine to do the actual work and then return to BASIC to print the answers.
 
This program is a proof of concept, really, and will only work with 8-bit values. In addition, with 1k of RAM there is only space for the first of the shifts/rotates; the others could be implemented along exactly the same lines.
 
The disassembly of the Z80 code would be:
<syntaxhighlight lang="z80asm"> org 4084
3a 83 40 ld a, (4083)
47 ld b, a
3a 82 40 ld a, (4082)
a0 and b
00 nop ; negate and shift instructions take 2 bytes
06 00 ld b, 0
4f ld c, a ; value in BC reg pair is returned to BASIC
c9 ret</syntaxhighlight>
We then use <code>POKE</code> statements to replace the <code>and</code> instruction with each successive operation we want to perform.
 
Note that the left shift instruction shifts by one bit at a time, so we need a loop. The present program has the loop written in BASIC, because it seemed sensible to use BASIC for anything we could use it for and only drop into machine code when there was no alternative; it would of course be faster to do the whole thing in machine code.
 
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
40 POKE 16514,A
50 POKE 16515,B
60 LET ADDR=16516
70 LET R$="3A8340473A8240A00006004FC9"
80 POKE ADDR,CODE R$*16+CODE R$(2)-476
90 LET R$=R$(3 TO )
100 LET ADDR=ADDR+1
110 IF R$<>"" THEN GOTO 80
120 PRINT A;" AND ";B;" = ";USR 16516
130 POKE 16523,176
140 PRINT A;" OR ";B;" = ";USR 16516
150 POKE 16523,168
160 PRINT A;" XOR ";B;" = ";USR 16516
170 POKE 16523,237
180 POKE 16524,68
190 PRINT "NOT ";A;" = ";USR 16516
200 POKE 16523,203
210 POKE 16524,39
220 FOR I=1 TO B
230 POKE 16514,USR 16516
240 NEXT I
250 PRINT A;" << ";B;" = ";PEEK 16514</syntaxhighlight>
{{in}}
<pre>21
3</pre>
{{out}}
<pre>21 AND 3 = 1
21 OR 3 = 23
21 XOR 3 = 22
NOT 21 = 235
21 << 3 = 168</pre>
 
==={{header|Tiny BASIC}}===
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
REM B = second number
REM C = result
REM P = current bit position
REM U = number of on bits at position P, or carry flag for rotate ops
REM Z = logic gate selection, then target number of on bits
 
10 LET P = 16384
LET F = 0
PRINT "1. A and B"
PRINT "2. A or B"
PRINT "3. A xor B"
PRINT "4. not A"
PRINT "5. A shr B"
PRINT "6. A shl B"
PRINT "7. A ror B"
PRINT "8. A rol B"
PRINT "Select a bitwise operation."
INPUT Z
IF Z < 1 THEN GOTO 10
IF Z > 8 THEN GOTO 10
11 PRINT "What is A? "
INPUT A
IF A < 0 THEN GOTO 11
IF Z = 4 THEN GOTO 15
12 PRINT "What is B?"
INPUT B
IF B < 0 THEN GOTO 12
15 GOSUB 100 + 10*Z
PRINT "The result is ", C,"."
END
110 LET Z = 2
GOSUB 500
RETURN
120 LET Z = 0
GOSUB 500
LET A = C
GOSUB 140
RETURN
130 LET Z = 1
GOSUB 500
LET A = C
GOSUB 140
RETURN
140 LET C = 32767 - A
RETURN
150 IF B = 0 THEN RETURN
LET A = A / 2
LET B = B - 1
GOTO 150
160 IF B = 0 THEN RETURN
IF A > P THEN LET A = A - P
LET A = A * 2
LET B = B - 1
GOTO 160
170 IF B = 0 THEN RETURN
LET U = 0
IF 2*(A/2) <> A THEN LET U = 1
LET A = A / 2 + U*P
LET B = B - 1
LET C = A
GOTO 170
180 IF B = 0 THEN RETURN
LET U = 0
IF A >= P THEN LET U = 1
LET A = (A-F*P)*2 + U
LET B = B - 1
LET C = A
GOTO 180
500 LET U = 0
IF B >= P THEN LET U = 1
IF A >= P THEN LET U = U + 1
IF U = Z THEN LET C = C + P
IF A >= P THEN LET A = A - P
IF B >= P THEN LET B = B - P
LET P = P / 2
IF P = 0 THEN RETURN
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}}==
<langsyntaxhighlight BASIC256lang="basic256"># bitwise operators - floating point numbers will be cast to integer
a = 0b00010001
b = 0b11110000
print a
print int(a * 2) # right shift left (multiply by 2)
print a \ 2 # left 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 350 ⟶ 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 424 ⟶ 2,605:
)
exit /b
</syntaxhighlight>
</lang>
 
Sample output
Line 469 ⟶ 2,650:
11111101000000000000000000000001
</pre>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> number1% = &89ABCDEF
number2% = 8
Line 482 ⟶ 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}}==
<syntaxhighlight lang="beeswax">#eX~T~T_#
###>N{` AND `~{~` = `&{Nz1~3J
UXe#
##>{` OR `~{~` = `|{Nz1~5J
UXe#
##>{` XOR `~{~` = `${Nz1~7J
UXe#
##>`NOT `{` = `!{Nz1~9J
UXe#
##>{` << `~{~` = `({Nz1~9PPJ
UXe#
##>{` >>> `~{~` = `){` (logical shift right)`N7F+M~1~J
UXe#
##>{` ROL `~{~` = `[{N7F+P~1~J
UXe#
##>{` ROR `~{~` = `]{NN8F+P~1~J
UXe#
##>`Arithmetic shift right is not originally implemented in beeswax.`N q
qN`,noitagen yb dezilaer eb nac srebmun evitagen rof RSA ,yllacinhcet tuB`N<
##>`logical shift right, and negating the result again:`NN7F++~1~J
UXe# #>e#
#>~1~[&'pUX{` >> `~{~` = `){` , interpreted as (positive) signed Int64 number (MSB=0), equivalent to >>>`NN;
###
>UX`-`!P{M!` >> `~{~` = `!)!`-`M!{` , interpreted as (negative) signed Int64 number (MSB=1)`NN;
#>e#</syntaxhighlight>
 
Example:
<syntaxhighlight lang="julia">
julia> beeswax("Bitops.bswx",0,0.0,Int(20000))
i9223653511831486512
i48
 
9223653511831486512 AND 48 = 48
9223653511831486512 OR 48 = 9223653511831486512
9223653511831486512 XOR 48 = 9223653511831486464
NOT 9223653511831486512 = 9223090561878065103
9223653511831486512 << 48 = 13510798882111488
9223653511831486512 >>> 48 = 32769 (logical shift right)
9223653511831486512 ROL 48 = 13651540665434112
9223653511831486512 ROR 48 = 3178497
 
Arithmetic shift right is not originally implemented in beeswax.
 
But technically, ASR for negative numbers can be realized by negation,
logical shift right, and negating the result again:
 
-9223090561878065104 >> 48 = -32767 , interpreted as (negative) signed Int64 number (MSB=1)</syntaxhighlight>
 
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
<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
>v>v>v>v < > ^
>#A 1 $^ ^ <
B 6^ <
^>^>^>^1 C |!`5p18:+1g18$ <
^ 9 p#p17*93p189p150 < >61g71g81gg+71g81gpv D
>071g81gp v ^ <
AND >+2\`!#^_> v
XOR +2% #^_> v
OR +1\`!#^_> v
NOT ! #^_> v
LSHFT 0 #^_>48*71g3+81gp v
RSHFT $ 48*71g3+81gp #^_>v E
END v #^_> >61g2*61pv
@ F
v_^# `2:<
>71g81gg.48*71g2+81gp79*1-71g2+81g1+pv
^ <_v#!`2p15:+1g15p18+1g18<
^ < G
 
</syntaxhighlight>
The labelled points (1 to G) are:
1. Read in A and B,
2. Set the current operating row (R) to 4,
3. Set the current bit value (M) to 64,
4. Set Current operating column (C) to 3,
5. Check if M > A (i.e. bit is 0 or 1),
6. Write the bit value into location (R,C),
7. A = A - M,
8. M = M/2,
9. C++,
A&B. Storage of corresponding bits,
C. Initialise R & C to operation storage (OP) and M to 1,
D. Increment OP by M if true,
E. M = M*2,
F (2 rows below). Print value of OP, increment operation to perform by moving ">" down,
G. If doing the NOT, LSHFT or RSHFT (current operation to perform > 3) only read A.
 
The code requires input be separated by spaces and only works for numbers less than 128, due to form of bit storage and ASCII locations not able to store beyond 127. Overflow will happen if 127 is shifted left due to aforementioned ASCII limit in most Befunge-93 interpreters.
 
'''Inputs''':
<pre>
21 3
</pre>
 
{{out}}
<pre>
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 498 ⟶ 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++}}==
{{trans|C}}
<lang cpp>#include <iostream>
 
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n'; // Note: parentheses are needed because & has lower precedence than <<
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
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 c = a;
std::cout << "c sra b: " << (c >> b) << '\n'; // logical right shift (guaranteed)
// there are no rotation operators in C++
}</lang>
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">static void bitwise(int a, int b)
{
Console.WriteLine("a and b is {0}", a & b);
Line 541 ⟶ 2,814:
// the operator performs a logical shift right
// there are no rotation operators in C#
}</langsyntaxhighlight>
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <iostream>
 
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n'; // Note: parentheses are needed because & has lower precedence than <<
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
 
// Note: the C/C++ shift operators are not guaranteed to work if the shift count (that is, b)
// is negative, or is greater or equal to the number of bits in the integer being shifted.
std::cout << "a shl b: " << (a << b) << '\n'; // Note: "<<" is used both for output and for left shift
std::cout << "a shr b: " << (a >> b) << '\n'; // typically arithmetic right shift, but not guaranteed
unsigned int ua = a;
std::cout << "a lsr b: " << (ua >> b) << '\n'; // logical right shift (guaranteed)
 
// there are no rotation operators in C++, but as of c++20 there is a standard-library rotate function.
// The rotate function works for all rotation amounts, but the integer being rotated must always be an
// unsigned integer.
std::cout << "a rol b: " << std::rotl(ua, b) << '\n';
std::cout << "a ror b: " << std::rotr(ua, b) << '\n';
}</syntaxhighlight>
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(bit-and x y)
(bit-or x y)
(bit-xor x y)
Line 550 ⟶ 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 561 ⟶ 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 585 ⟶ 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 609 ⟶ 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 649 ⟶ 2,968:
 
f(10,2)
</syntaxhighlight>
</lang>
 
output
<syntaxhighlight lang="text">
> coffee foo.coffee
and 2
Line 660 ⟶ 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 671 ⟶ 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 682 ⟶ 3,000:
 
(defun shr (x width bits)
"Compute bitwise rigthright shift of x by 'bits' bits, represented on 'width' bits"
(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 698 ⟶ 3,016:
 
(defun rotr (x width bits)
"Compute bitwise rigthright rotation of x by 'bits' bits, represented on 'width' bits"
(logior (logand (ash x (- (mod bits width)))
(1- (ash 1 width)))
(logand (ash x (- width (mod bits width)))
(1- (ash 1 width)))))
</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 728 ⟶ 3,045:
 
testBit(a, b);
}</langsyntaxhighlight>
{{out}}
<pre>Input: a = 255, b = 2
Line 740 ⟶ 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 755 ⟶ 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 777 ⟶ 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 810 ⟶ 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 6.x :
<lang elena>#define system.
#define<syntaxhighlight lang="elena">import extensions.;
 
#class(extension) testOp
{
#method bitwiseTest : (y)
[{
console writeLine:.printLine(self:," and ":,y:," = ":(,self and:& y).;
console writeLine:.printLine(self:," or ":,y:," = ":(,self or:| y).;
console writeLine:.printLine(self:," xor ":,y:," = ":(,self xor:^ y).;
console writeLine:.printLine("not ":,self:," = ":(,self not.BInverted).;
console writeLine:.printLine(self:," shr ":,y:," = ":(,self shift &index:.shiftRight(y).);
console writeLine:.printLine(self:," shl ":,y:," = ":(,self shift &index:.shiftLeft(y negative)).;
]}
}
 
#symbolpublic program =()
{
[
console readLine:.loadLineTo(Integer new) Integer()).bitwiseTest:(console readLine:.loadLineTo(Integer new Integer())).
}</syntaxhighlight>
].</lang>
{{out}}
<pre>
Line 844 ⟶ 3,227:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Bitwise_operation do
use Bitwise
Line 865 ⟶ 3,248:
end
 
Bitwise_operation.test</langsyntaxhighlight>
 
{{out}}
Line 885 ⟶ 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 903 ⟶ 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 913 ⟶ 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 925 ⟶ 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 936 ⟶ 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 946 ⟶ 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 969 ⟶ 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 1,000 ⟶ 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 1,022 ⟶ 3,398:
write(*,fmt2) 'or : ', a,' | ',b,' = ',ior(a, b),ior(a, b)
write(*,fmt2) 'xor : ', a,' ^ ',b,' = ',ieor(a, b),ieor(a, b)
write(*,fmt2) 'lsh : ', a,' << ',b,' = ',ishftshiftl(a, absb),shiftl(a,b)) !since F2008, otherwise use ishft(a, abs(b))
write(*,fmt2) 'rsh : ', a,' >> ',b,' = ',ishftshiftr(a, -absb),shiftr(a,b)) !since F2008, otherwise use ishft(a, -abs(b))
write(*,fmt2) 'not : ', a,' ~ ',b,' = ',not(a),not(a)
write(*,fmt2) 'rot : ', a,' r ',b,' = ',ishftc(a,-abs(b)),ishftc(a,-abs(b))
Line 1,030 ⟶ 3,406:
 
end program bits_rosetta
</syntaxhighlight>
</lang>
Output
<syntaxhighlight lang="text">
Input a= 14 b= 3
AND : 00000000000000000000000000001110 & 00000000000000000000000000000011 = 00000000000000000000000000000010 2
Line 1,041 ⟶ 3,417:
NOT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11111111111111111111111111110001 -15
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823
</syntaxhighlight>
</lang>
=={{header|Free Pascal}}==
<syntaxhighlight lang="pascal">program Bitwise;
{$mode objfpc}
var
// Pascal uses a native int type as a default literal type
// Make sure the operants work on an exact type.
x:shortint = 2;
y:ShortInt = 3;
begin
Writeln('2 and 3 = ', x and y);
Writeln('2 or 3 = ', x or y);
Writeln('2 xor 3 = ', x xor y);
Writeln('not 2 = ', not x);
Writeln('2 shl 3 = ', x >> y);
Writeln('2 shr 3 = ', x << y);
writeln('2 rol 3 = ', rolbyte(x,y));
writeln('2 ror 3 = ', rorbyte(x,y));
writeln('2 sar 3 = ', sarshortint(x,y));
Readln;
end.</syntaxhighlight>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits)
 
' FB doesn't have built-in logical shift right or rotation operators
' but, as they're not difficult to implement, I've done so below.
 
Function lsr(x As Const Integer, y As Const Integer) As Integer
Dim As UInteger z = x
Return z Shr y
End Function
Function rol(x As Const Integer, y As Const UInteger) As Integer
Dim z As Integer = x
Dim high As Integer
For i As Integer = 1 To y
high = Bit(z, 63)
For j As Integer = 62 To 0 Step -1
If Bit(z, j) Then
z = BitSet(z, j + 1)
Else
z = BitReset (z, j + 1)
End If
Next j
If high Then
z = BitSet(z, 0)
Else
z = BitReset(z, 0)
End If
Next i
Return z
End Function
 
Function ror(x As Const Integer, y As Const UInteger) As Integer
Dim z As Integer = x
Dim low As Integer
For i As Integer = 1 To y
low = Bit(z, 0)
For j As Integer = 1 To 63
If Bit(z, j) Then
z = BitSet(z, j - 1)
Else
z = BitReset (z, j - 1)
End If
Next j
If low Then
z = BitSet(z, 63)
Else
z = BitReset(z, 63)
End If
Next i
Return z
End Function
 
Sub bitwise(x As Integer, y As Integer)
Print "x = "; x
Print "y = "; y
Print "x AND y = "; x And y
Print "x OR y = "; x Or y
Print "x XOR y = "; x XOr y
Print "NOT x = "; Not x
Print "x SHL y = "; x Shl y
Print "x SHR y = "; x Shr y
Print "x LSR y = "; lsr(x, y)
Print "x ROL y = "; rol(x, y)
Print "x ROR y = "; ror(x, y)
End Sub
 
bitwise -15, 3
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
x = -15
y = 3
x AND y = 1
x OR y = -13
x XOR y = -14
NOT x = 14
x SHL y = -120
x SHR y = -2
x LSR y = 2305843009213693950
x ROL y = -113
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)
def fn rotr( b as long, n as long ) as long = (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 )
 
HandleEvents</syntaxhighlight>
 
Output:
<pre>
Input: a = 255 b = 2
 
AND : a && b = 00000000000000000000000000000010 : 2
NAND : a ^& b = 00000000000000000000000011111101 : 253
OR : a || b = 00000000000000000000000011111111 : 255
NOR : a ^| b = 11111111111111111111111111111111 : -1
XOR : a ^^ b = 00000000000000000000000011111101 : 253
NOT : not a = 11111111111111111111111100000000 : -256
 
Left shift : a << b = 00000000000000000000001111111100 : 1020
Right shift : a >> b = 00000000000000000000000000111111 : 63
 
Rotate left : fn rotl( a, b ) = 11111111111111111111111111111111 : -1
Rotate right : fn rotr( a, b ) = 11000000000000000000000000111111 : -1073741761
</pre>
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
 
func bitwise(a, b int16) (and, or, xor, not, shl, shr, ras, rol, ror int16) {
fmt.Printf("a: %016b\n", uint16(a))
// the first four are easy
fmt.Printf("b: %016b\n", uint16(b))
and = a & b
or = a | b
xor = a ^ b
not = ^a
 
// Bitwise logical operations
// for all shifts, the right operand (shift distance) must be unsigned.
fmt.Printf("and: %016b\n", uint16(a&b))
// use abs(b) for a non-negative value.
fmt.Printf("or: %016b\n", uint16(a|b))
if b < 0 {
fmt.Printf("xor: %016b\n", uint16(a^b))
b = -b
fmt.Printf("not: %016b\n", uint16(^a))
}
ub := uint(b)
 
if b < 0 {
shl = a << ub
fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).")
// for right shifts, if the left operand is unsigned, Go performs
return
// a logical shift; if signed, an arithmetic shift.
}
shr = int16(uint16(a) >> ub)
ua := uint16(a)
ras = a >> ub
ub := uint32(b)
 
// Logical shifts (unsigned left operand)
// rotates
fmt.Printf("shl: %016b\n", uint16(ua<<ub))
rol = a << ub | int16(uint16(a) >> (16-ub))
fmt.Printf("shr: %016b\n", ror = int16(uint16(a) ua>> ub) | a << (16-ub)
 
return
// Arithmetic shifts (signed left operand)
fmt.Printf("las: %016b\n", uint16(a<<ub))
fmt.Printf("ras: %016b\n", uint16(a>>ub))
 
// Rotations
fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub))))
fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))
}
 
func main() {
var a, b int16 = -460, 6
and, or, xor, not, shl, shr, ras, rol, ror := bitwise(a, b)
}</syntaxhighlight>
fmt.Printf("a: %016b\n", uint16(a))
fmt.Printf("b: %016b\n", uint16(b))
fmt.Printf("and: %016b\n", uint16(and))
fmt.Printf("or: %016b\n", uint16(or))
fmt.Printf("xor: %016b\n", uint16(xor))
fmt.Printf("not: %016b\n", uint16(not))
fmt.Printf("shl: %016b\n", uint16(shl))
fmt.Printf("shr: %016b\n", uint16(shr))
fmt.Printf("ras: %016b\n", uint16(ras))
fmt.Printf("rol: %016b\n", uint16(rol))
fmt.Printf("ror: %016b\n", uint16(ror))
}</lang>
Output:
<pre>a: 1111111000110100
<pre>
a: 1111111000110100
b: 0000000000000110
and: 0000000000000100
Line 1,099 ⟶ 3,618:
shl: 1000110100000000
shr: 0000001111111000
las: 1000110100000000
ras: 1111111111111000
rol: 1000110100111111
ror: 1101001111111000</pre>
</pre>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def bitwise = { a, b ->
println """
a & b = ${a} & ${b} = ${a & b}
Line 1,115 ⟶ 3,633:
a >>> b = ${a} >>> ${b} = ${a >>> b} logical (zero-filling) shift
"""
}</langsyntaxhighlight>
 
Program:
<syntaxhighlight lang ="groovy">bitwise(-15,3)</langsyntaxhighlight>
 
Output:
Line 1,128 ⟶ 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
local aPar := hb_AParams()
local nRot
if ! Empty( aPar )
n1 := Val( aPar[1] )
hb_Adel( aPar, 1, .T. )
if ! Empty( aPar )
n2 := Val( aPar[1] )
endif
endif
clear screen
? "Bitwise operations with two integers"
? "n1 =", hb_ntos(n1)
? "n2 =", hb_ntos(n2)
? "------------------------------------"
? "AND -->", hb_BitAnd( n1, n2 )
? "OR -->", hb_BitOr( n1, n2 )
? "XOR -->", hb_BitXor( n1, n2 )
? "NOT -->", hb_BitNot( n1 )
? "LSHIFT -->", hb_bitShift( n1, n2 )
? "RSHIFT -->", hb_bitShift( n1, -n2 )
? "RarSHIFT -->", hb_bitShift( n1, -n2 )
/* left/right rotation is not implemented, but we can use inline C-code to do it */
/* rotate n1 to the left by n2 bits */
nRot := hb_Inline( n1, n2 ) {
HB_UINT x = hb_parni( 1 ), s = hb_parni( 2 );
hb_retni( (x << s) | (x >> (-s & 31)) );
} // (x << s) | (x >> (32 - s));
? "Rotate left -->", nRot
 
/* rotate n1 to the right by n2 bits */
nRot := HB_INLINE( n1, n2 ){
HB_UINT x = hb_parni( 1 ), s = hb_parni( 2 );
hb_retni( (x >> s) | (x << (32 - s)) );
}
? "Rotate right -->", nRot
return
 
</syntaxhighlight>
Output:
Bitwise operations with two integers
n1 = 42
n2 = 2
------------------------------------
AND --> 2
OR --> 42
XOR --> 40
NOT --> -43
LSHIFT --> 168
RSHIFT --> 10
RarSHIFT --> 10
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 ()
bitwise a b = do
mapM_
print $ a .&. b
print $ a .|. bprint
print $ [ a `xor`.&. b
print $ complement, a .|. b
, a `xor` b
print $ shiftL a b -- left shift
, complement a
print $ shiftR a b -- arithmetic right shift
, shiftL a b -- left shift
print $ shift a b -- You can also use the "unified" shift function; positive is for left shift, negative is for right shift
, shiftR a b -- arithmetic right shift
print $ shift a (-b)
, shift a b -- You can also use the "unified" shift function;
print $ rotateL a b -- rotate left
-- positive is for left shift, negative is for right shift
print $ rotateR a b -- rotate right
, shift a (-b)
print $ rotate a b -- You can also use the "unified" rotate function; positive is for left rotate, negative is for right rotate
, rotateL a b -- rotate left
print $ rotate a (-b)
, rotateR a b -- rotate right
, rotate a b -- You can also use the "unified" rotate function;
-- positive is for left rotate, negative is for right rotate
, rotate a (-b)
]
 
main :: IO ()
main = bitwise 255 170</syntaxhighlight>
{{Out}}
<pre>170
255
85
-256
0
0
0
0
1121501860331520
1069547520
1121501860331520
1069547520</pre>
 
main = bitwise 255 170</lang>
If you were shifting Words (unsigned integers) instead of Ints, then the shift would be automatically logical shifts:
import Data.Word
Line 1,156 ⟶ 3,755:
=={{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}}==
 
<syntaxhighlight lang="hpppl">EXPORT BITOPS(a, b)
BEGIN
PRINT(BITAND(a, b));
PRINT(BITOR(a, b));
PRINT(BITXOR(a, b));
PRINT(BITNOT(a));
PRINT(BITSL(a, b));
PRINT(BITSR(a, b));
// HPPPL has no builtin rotates or arithmetic right shift.
END;</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
bitdemo(255,2)
bitdemo(-15,3)
Line 1,182 ⟶ 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 1,206 ⟶ 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 1,225 ⟶ 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 1,238 ⟶ 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 1,258 ⟶ 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 1,277 ⟶ 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 1,295 ⟶ 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}}==
<syntaxhighlight lang="julia"># Version 5.2
@show 1 & 2 # AND
@show 1 | 2 # OR
@show 1 ^ 2 # XOR -- for Julia 6.0 the operator is `⊻`
@show ~1 # NOT
@show 1 >>> 2 # SHIFT RIGHT (LOGICAL)
@show 1 >> 2 # SHIFT RIGHT (ARITMETIC)
@show 1 << 2 # SHIFT LEFT (ARITMETIC/LOGICAL)
 
A = BitArray([true, true, false, false, true])
@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>
 
{{out}}
<pre>
1 & 2 = 0
1 | 2 = 3
1 ^ 2 = 1
~1 = -2
1 >>> 2 = 0
1 >> 2 = 0
1 << 2 = 4
A = Bool[true,true,false,false,true]
ror(A,1) = Bool[true,true,true,false,false]
ror(A,2) = Bool[false,true,true,true,false]
ror(A,5) = Bool[true,true,false,false,true]
rol(A,1) = Bool[true,false,false,true,true]
rol(A,2) = Bool[false,false,true,true,true]
rol(A,5) = Bool[true,true,false,false,true]
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
fun main() {
// inferred type of x and y is Int (32-bit signed integer)
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.rotateLeft(y)}")
println("x ROR y = ${x.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
x ASR y = 2
x LSR y = 2
x ROL y = 40
x ROR y = -2147483646
</pre>
 
=={{header|LFE}}==
 
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
(io:format '"~p~n" (list (band a b)))
(lambda (x) (io:format '"~p~n" `(list (bor a b,x)))
`(io:format '"~p~n" ,(list (bxorband a b)))
(io:format '"~p~n" ,(listbor (bnota a))b)
(io:format '"~p~n" (list ,(bslbxor a b)))
(io:format '"~p~n" ,(list (bsrbnot a b))))
,(bsl a b)
,(bsr a b)))
'ok)
 
(defun d2bdec->bin (x)
(x) (integer_to_list x 2))
 
(defun describe (func arg1 arg2 result)
(io:format "(~s ~s ~s): ~s~n"
(list func (dec->bin arg1) (dec->bin arg2) (dec->bin result))))
 
(defun bitwise
((a b 'binary)
(io:formatdescribe '"band" a b (~sband ~sa ~sb)): ~s~n"
(listdescribe "bandbor" (d2b a) (d2b b) (d2b (bandbor a b))))
(io:formatdescribe '"bxor" a b (~sbxor ~sa ~sb)): ~s~n"
(listdescribe "borbnot" (d2b a) (d2b b) (d2b (borbnot a b))))
(io:formatdescribe '"bsl" a b (~sbsl ~sa ~sb)): ~s~n"
(listdescribe "bxorbsr" (d2b a) (d2b b) (d2b (bxorbsr a b))))
</syntaxhighlight>
(io:format '"(~s ~s): ~s~n"
(list "bnot" (d2b a) (d2b (bnot a))))
(io:format '"(~s ~s ~s): ~s~n"
(list "bsl" (d2b a) (d2b b) (d2b (bsl a b))))
(io:format '"(~s ~s ~s): ~s~n"
(list "bsr" (d2b a) (d2b b) (d2b (bsr a b))))))
</lang>
 
Example usage:
<langsyntaxhighlight lang="lisp">
> (bitwise 255 170)
170
Line 1,347 ⟶ 4,081:
ok
>
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
Written as functions.
<syntaxhighlight lang="lb">
<lang lb>
' bitwise operations on byte-sized variables
 
Line 1,398 ⟶ 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:
<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}}==
<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 1,408 ⟶ 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 1,471 ⟶ 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 1,485 ⟶ 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 1,493 ⟶ 4,230:
a lshift b: 8160
a lshift -b: 7
-a ashift -b: -8</langsyntaxhighlight>
=={{header|LSE64}}==
 
{{incorrect|LSE64|No reason given.}}
<syntaxhighlight lang="lse64">over : 2 pick
2dup : over over
bitwise : \
" A=" ,t over ,h sp " B=" ,t dup ,h nl \
" A and B=" ,t 2dup & ,h nl \
" A or B=" ,t 2dup | ,h nl \
" A xor B=" ,t over ^ ,h nl \
" not A=" ,t ~ ,h nl
\ a \ 7 bitwise # hex literals</syntaxhighlight>
=={{header|Lua}}==
 
LuaBitOp implements bitwise functionality for Lua:
 
<langsyntaxhighlight lang="lua">local bit = require"bit"
 
local vb = {
Line 1,564 ⟶ 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 1,570 ⟶ 4,319:
& (and), | (or), ^^ (xor), << (logical shift left), >> (logical shift right)
and a unary operation ~ (negate).
==={{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:
=={{header|LSE64}}==
<syntaxhighlight lang="lua">a = 0xAA55AA55
{{incorrect|LSE64|No reason given.}}
b = 0x4
<lang lse64>over : 2 pick
print(string.format("%8X and %8X = %16X", a, b, a&b))
2dup : over over
print(string.format("%8X or %8X = %16X", a, b, a|b))
print(string.format("%8X xor %8X = %16X", a, b, a~b))
bitwise : \
print(string.format("%8s not %8X = %16X", "", a, ~a))
" A=" ,t over ,h sp " B=" ,t dup ,h nl \
print(string.format("%8X shl %8X = %16X", a, b, a<<b))
" A and B=" ,t 2dup & ,h nl \
print(string.format("%8X shr %8X = %16X", a, b, a>>b))
" A or B=" ,t 2dup | ,h nl \
-- not built-in, 32-bit substitutes provided:
" A xor B=" ,t over ^ ,h nl \
local function sar(x,n) return (x>>n) | (x&0x80000000==0 and 0 or (0xffffffff<<(32-n))&0xffffffff) end
" not A=" ,t ~ ,h nl
local function rol(x,n) return ((x<<n)&0xffffffff) | (x>>(32-n)) end
local function ror(x,n) return (x>>n) | ((x<<(32-n))&0xffffffff) end
\ a \ 7 bitwise # hex literals</lang>
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)))</syntaxhighlight>
{{out}}
<pre>AA55AA55 and 4 = 4
AA55AA55 or 4 = AA55AA55
AA55AA55 xor 4 = AA55AA51
not AA55AA55 = FFFFFFFF55AA55AA
AA55AA55 shl 4 = AA55AA550
AA55AA55 shr 4 = AA55AA5
AA55AA55 sar 4 = FAA55AA5
AA55AA55 rol 4 = A55AA55A
AA55AA55 ror 4 = 5AA55AA5</pre>
=={{header|Maple}}==
<syntaxhighlight lang="maple">
with(Bits):
bit:=proc(A,B)
local a,b,c,d,e,f,g,h,i,x,bitpow;
bitpow := 2^B:
a:=And(A,B);
b:=Not(A);
c:=Or(A,B);
d:=Xor(A,B);
#Left Shift
e:= irem(2*A,bitpow);
#Right Shift
f := iquo(A,2);
#Left Rotate
g:= irem(2*A,bitpow,'x')+x;
#Rightarithshift
i:= iquo(A,2)+bitpow/2*irem(A,bitpow/2);
return a,b,c,d,e,f,g,i;
end proc;
</syntaxhighlight>
=={{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 1,604 ⟶ 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 1,621 ⟶ 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 1,654 ⟶ 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 1,667 ⟶ 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 1,689 ⟶ 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 1,714 ⟶ 4,491:
BEGIN
Bitwise(255, 5);
END Bitwise.</langsyntaxhighlight>
 
Output:
Line 1,727 ⟶ 4,504:
c RightRotate b: f8000007
</pre>
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<doc>
<h2>bitwise operations</h2>
<p>Tectonics:
<br> nekoc bitwise.neko
<br> neko bitwise</p>
</doc>
*/
 
// Neko is a signed 31 bit integer VM, full 32 bit requires builtins
var int32_new = $loader.loadprim("std@int32_new", 1);
var int32_and = $loader.loadprim("std@int32_and", 2);
var int32_or = $loader.loadprim("std@int32_or", 2);
var int32_xor = $loader.loadprim("std@int32_xor", 2);
var int32_shl = $loader.loadprim("std@int32_shl", 2);
var int32_shr = $loader.loadprim("std@int32_shr", 2);
var int32_ushr = $loader.loadprim("std@int32_ushr", 2);
var int32_complement = $loader.loadprim("std@int32_complement", 1);
 
// Function to show bitwise operations on a,b
var bitwise = function(a, b) {
var ia = int32_new(a);
var ib = int32_new(b);
 
$print("Neko 32 bit integer library\n");
$print("a AND b: ", a, " ", b, " ", int32_and(ia, ib), "\n");
$print("a OR b: ", a, " ", b, " ", int32_or(ia, ib), "\n");
$print("a XOR b: ", a, " ", b, " ", int32_xor(ia, ib), "\n");
$print("ones complement a: ", a, " ", int32_complement(ia), "\n");
$print("a SHL b: ", a, " ", b, " ", int32_shl(ia, ib), "\n");
$print("a SHR b: ", a, " ", b, " ", int32_shr(ia, ib), "\n");
$print("a USHR b: ", a, " ", b, " ", int32_ushr(ia, ib), "\n");
$print("a ROL b: is not directly supported in Neko Int32\n");
$print("a ROR b: is not directly supported in Neko Int32\n");
 
$print("\nNormal Neko 31 bit signed integers\n");
a = $int(a);
b = $int(b);
$print("a AND b: ", a, " ", b, " ", a & b, "\n");
$print("a OR b: ", a, " ", b, " ", a | b, "\n");
$print("a XOR b: ", a, " ", b, " ", a ^ b, "\n");
$print("NOT a: is not directly supported in Neko syntax\n");
$print("a SHL b: ", a, " ", b, " ", a << b, "\n");
$print("a SHR b: ", a, " ", b, " ", a >> b, "\n");
$print("a USHR b: ", a, " ", b, " ", a >>> b, "\n");
$print("a ROL b: is not directly supported in Neko syntax\n");
$print("a ROR b: is not directly supported in Neko syntax\n");
}
 
// Pass command line arguments to the demo function
// initially as float, to ensure no internal bit truncation
var a = $float($loader.args[0]);
var b = $float($loader.args[1]);
if a == null a = 0;
if b == null b = 0;
 
bitwise(a,b);</syntaxhighlight>
 
{{out}}
<pre>prompt$ nekoc bitwise.neko
prompt$ neko bitwise 0x7fffffff 2
Neko 32 bit integer library
a AND b: 2147483647 2 2
a OR b: 2147483647 2 2147483647
a XOR b: 2147483647 2 2147483645
ones complement a: 2147483647 -2147483648
a SHL b: 2147483647 2 -4
a SHR b: 2147483647 2 536870911
a USHR b: 2147483647 2 536870911
a ROL b: is not directly supported in Neko Int32
a ROR b: is not directly supported in Neko Int32
 
Normal Neko 31 bit signed integers
a AND b: -1 2 2
a OR b: -1 2 -1
a XOR b: -1 2 -3
NOT a: is not directly supported in Neko syntax
a SHL b: -1 2 -4
a SHR b: -1 2 -1
a USHR b: -1 2 1073741823
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 1,741 ⟶ 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 1,750 ⟶ 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 1,780 ⟶ 4,637:
Pop $1
Pop $0
FunctionEnd</langsyntaxhighlight>
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<syntaxhighlight lang="oberon2">
MODULE Bitwise;
IMPORT
SYSTEM,
Out;
 
PROCEDURE Do(a,b: LONGINT);
VAR
x,y: SET;
BEGIN
x := SYSTEM.VAL(SET,a);y := SYSTEM.VAL(SET,b);
Out.String("a and b :> ");Out.Int(SYSTEM.VAL(LONGINT,x * y),0);Out.Ln;
Out.String("a or b :> ");Out.Int(SYSTEM.VAL(LONGINT,x + y),0);Out.Ln;
Out.String("a xor b :> ");Out.Int(SYSTEM.VAL(LONGINT,x / y),0);Out.Ln;
Out.String("a and ~b:> ");Out.Int(SYSTEM.VAL(LONGINT,x - y),0);Out.Ln;
Out.String("~a :> ");Out.Int(SYSTEM.VAL(LONGINT,-x),0);Out.Ln;
Out.String("a left shift b :> ");Out.Int(SYSTEM.VAL(LONGINT,SYSTEM.LSH(x,b)),0);Out.Ln;
Out.String("a right shift b :> ");Out.Int(SYSTEM.VAL(LONGINT,SYSTEM.LSH(x,-b)),0);Out.Ln;
Out.String("a left rotate b :> ");Out.Int(SYSTEM.VAL(LONGINT,SYSTEM.ROT(x,b)),0);Out.Ln;
Out.String("a right rotate b :> ");Out.Int(SYSTEM.VAL(LONGINT,SYSTEM.ROT(x,-b)),0);Out.Ln;
Out.String("a arithmetic left shift b :> ");Out.Int(SYSTEM.VAL(LONGINT,ASH(a,b)),0);Out.Ln;
Out.String("a arithmetic right shift b :> ");Out.Int(SYSTEM.VAL(LONGINT,ASH(a,-b)),0);Out.Ln
END Do;
 
BEGIN
Do(10,2);
END Bitwise.
</syntaxhighlight>
{{out}}
<pre>
a and b :> 2
a or b :> 10
a xor b :> 8
a and ~b:> 8
~a :> -11
a left shift b :> 40
a right shift b :> 2
a left rotate b :> 40
a right rotate b :> -2147483646
a arithmetic left shift b :> 40
a arithmetic right shift b :> 2
</pre>
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
 
bundle Default {
Line 1,799 ⟶ 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 1,810 ⟶ 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 1,826 ⟶ 4,724:
endfunction
 
bitops(0x1e, 0x3);</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
There is no built-in for not and rotation
 
<langsyntaxhighlight Oforthlang="oforth">func: bitwise(a, b)
{
a b bitAnd println
a b bitOr println
a b bitXor println
a bitLeft(b) println
a bitRight(b) println ;</syntaxhighlight>
}</lang>
 
=={{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 1,861 ⟶ 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 1,872 ⟶ 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 1,886 ⟶ 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 1,898 ⟶ 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 1,915 ⟶ 4,805:
print 'a << b: ', $a << $b, "\n"; # left shift
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift
}</langsyntaxhighlight>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2015.12}}
<lang perl6>constant MAXINT = uint.Range.max;
constant BITS = MAXINT.base(2).chars;
 
# define rotate ops for the fun of it
multi sub infix:<⥁>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).list.rotate(b).reverse] }
multi sub infix:<⥀>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).reverse.rotate(b)] }
 
sub int-bits (Int $a, Int $b) {
say '';
say_bit "$a", $a;
say '';
say_bit "2's complement $a", +^$a;
say_bit "$a and $b", $a +& $b;
say_bit "$a or $b", $a +| $b;
say_bit "$a xor $b", $a +^ $b;
say_bit "$a unsigned shift right $b", ($a +& MAXINT) +> $b;
say_bit "$a signed shift right $b", $a +> $b;
say_bit "$a rotate right $b", $a ⥁ $b;
say_bit "$a shift left $b", $a +< $b;
say_bit "$a rotate left $b", $a ⥀ $b;
}
 
int-bits(7,2);
int-bits(-65432,31);
 
sub say_bit ($message, $value) {
printf("%30s: %{'0' ~ BITS}b\n", $message, $value +& MAXINT);
}</lang>
{{out}}
<pre> 7: 0000000000000000000000000000000000000000000000000000000000000111
 
2's complement 7: 1111111111111111111111111111111111111111111111111111111111111000
7 and 2: 0000000000000000000000000000000000000000000000000000000000000010
7 or 2: 0000000000000000000000000000000000000000000000000000000000000111
7 xor 2: 0000000000000000000000000000000000000000000000000000000000000101
7 unsigned shift right 2: 0000000000000000000000000000000000000000000000000000000000000001
7 signed shift right 2: 0000000000000000000000000000000000000000000000000000000000000001
7 rotate right 2: 1100000000000000000000000000000000000000000000000000000000000001
7 shift left 2: 0000000000000000000000000000000000000000000000000000000000011100
7 rotate left 2: 0000000000000000000000000000000000000000000000000000000000011100
 
-65432: 1111111111111111111111111111111111111111111111110000000001101000
 
2's complement -65432: 0000000000000000000000000000000000000000000000001111111110010111
-65432 and 31: 0000000000000000000000000000000000000000000000000000000000001000
-65432 or 31: 1111111111111111111111111111111111111111111111110000000001111111
-65432 xor 31: 1111111111111111111111111111111111111111111111110000000001110111
-65432 unsigned shift right 31: 0000000000000000000000000000000111111111111111111111111111111111
-65432 signed shift right 31: 1111111111111111111111111111111111111111111111111111111111111111
-65432 rotate right 31: 1111111111111110000000001101000111111111111111111111111111111111
-65432 shift left 31: 1111111111111111100000000011010000000000000000000000000000000000
-65432 rotate left 31: 1111111111111111100000000011010001111111111111111111111111111111</pre>
 
=={{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>enum SHL, SAR, SHR, ROL, ROR
<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>
function bitop(atom a, integer b, integer op)
<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>
atom res
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span>
#ilASM{
<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>
[32]
<span style="color: #000080;font-style:italic;">-- Note: Phix doesn't quietly discard high bits...</span>
mov eax,[a]
<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>
call :%pLoadMint
<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>
mov ecx,[b]
<span style="color: #000080;font-style:italic;">-- Note: Phix doesn't really do "unsigned numbers",
mov edx,[op]
-- Should you want to treat 4G-1 as -1 then:</span>
cmp dl,SHL
<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>
jne @f
<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>
shl eax,cl
<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>
jmp :storeres
<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>
@@:
<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>
cmp dl,SAR
<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>
jne @f
<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>
sar eax,cl
<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>
jmp :storeres
<span style="color: #008080;">else</span>
@@:
<span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span>
cmp dl,SHR
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
jne @f
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
shr eax,cl
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
jmp :storeres
@@:
<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>
cmp dl,ROL
<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: #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>
jne @f
<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: #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>
rol eax,cl
<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: #7060A8;">xor_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>
jmp :storeres
<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: #7060A8;">not_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>
cmp dl,ROR
<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>
jne @f
<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;">" shr(%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;">SHR</span><span style="color: #0000FF;">)})</span>
ror eax,cl
<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;">" rol(%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;">ROL</span><span style="color: #0000FF;">)})</span>
jmp :storeres
<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;">" ror(%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;">ROR</span><span style="color: #0000FF;">)})</span>
@@:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
int3
::storeres
<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>
lea edi,[res]
<!--</syntaxhighlight>-->
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
}
return res
end function
 
procedure bitwise(atom a, atom b)
printf(1,"and_bits(%b,%b) = %032b\n",{a,b,and_bits(a,b)})
printf(1," or_bits(%b,%b) = %032b\n",{a,b, or_bits(a,b)})
printf(1,"xor_bits(%b,%b) = %032b\n",{a,b,xor_bits(a,b)})
printf(1,"not_bits(%b) = %032b\n",{a,not_bits(a)})
printf(1," shl(%b,%b) = %032b\n",{a,b,bitop(a,b,SHL)})
printf(1," sar(%b,%b) = %032b\n",{a,b,bitop(a,b,SAR)})
printf(1," shr(%b,%b) = %032b\n",{a,b,bitop(a,b,SHR)})
printf(1," rol(%b,%b) = %032b\n",{a,b,bitop(a,b,ROL)})
printf(1," ror(%b,%b) = %032b\n",{a,b,bitop(a,b,ROR)})
end procedure
 
bitwise(0x800000FE,7)</lang>
{{out}}
<pre>
Line 2,076 ⟶ 4,861:
ror(10000000000000000000000011111110,111) = 11111101000000000000000000000001
</pre>
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">6 var a 3 var b
 
def tab
9 tochar print
enddef
 
def printBits
8 int>bit reverse print nl
enddef
 
a print " = " print tab a printBits
b print " = " print tab b printBits
tab "------------------------" print nl
"AND = " print tab a b bitand printBits
"OR = " print tab a b bitor printBits
"XOR = " print tab a b bitxor printBits
"NOT = " print tab a bitnot printBits</syntaxhighlight>
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function bitwise($a, $b)
{
function zerofill($a,$b) {
Line 2,092 ⟶ 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 2,100 ⟶ 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 2,114 ⟶ 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 2,138 ⟶ 4,939:
 
: (>> -1 -16)
-> -32</langsyntaxhighlight>
=={{header|Pike}}==
Rotate operations are not available
<syntaxhighlight lang="pike">
void bitwise(int a, int b)
{
write("a and b: %d\n", a & b);
write("a or b: %d\n", a | b);
write("a xor b: %d\n", a ^ b);
write("not a: %d\n", ~a);
write("a << b: 0x%x\n", a << b);
write("a >> b: %d\n", a >> b);
// ints in Pike do not overflow, if a particular size of the int
// is desired then cap it with an AND operation
write("a << b & 0xffffffff (32bit cap): 0x%x\n",
a << b & 0xffffffff);
}
 
void main()
{
bitwise(255, 30);
}
</syntaxhighlight>
{{Out}}
<pre>
a and b: 30
a or b: 255
a xor b: 225
not a: -256
a << b: 0x3fc0000000
a >> b: 0
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 2,161 ⟶ 4,993:
u = s ^ t; /* exclusive or */
 
/* Built-in rotate functions are not available. */
/* They can be readily implemented by the user, though: */
 
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 2,177 ⟶ 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}}
<syntaxhighlight lang="powershell">$X -band $Y
$X -bor $Y
$X -bxor $Y
-bnot $X</syntaxhighlight>
{{works with|PowerShell|3.0}}
<syntaxhighlight lang="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))</syntaxhighlight>
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Bitwise(a, b)
Debug a & b ; And
Debug a | b ;Or
Line 2,212 ⟶ 5,057:
!mov dword [p.v_Temp], edx
Debug Temp
EndProcedure</langsyntaxhighlight>
=={{header|Python}}==
===Python 3===
Python has variable length integers. Usually implementations require
fixed-width integers. This we get by &-ing values with a mask of all
ones of sufficient length.
Below we use a combination of a mask and zero-extended fixed-width
binary output formatting in calculations and result displays.
 
<syntaxhighlight lang="python">def bitwise_built_ins(width, a, b):
=={{header|PowerShell}}==
mask = (1 << width) - 1
Logical right shift and rotations are not supported in PowerShell.
print(f"""\
{{works with|PowerShell|2.0}}
AND: 0b{a :0{width}b}
<lang PowerShell>$X -band $Y
& 0b{b :0{width}b}
$X -bor $Y
= 0b{(a & b) & mask :0{width}b}
$X -bxor $Y
-bnot $X</lang>
OR: 0b{a :0{width}b}
| 0b{b :0{width}b}
{{works with|PowerShell|3.0}}
= 0b{(a | b) & mask :0{width}b}
<lang PowerShell>$X -shl $Y
# Arithmetic right shift
XOR: 0b{a :0{width}b}
$X -shr $Y
^ 0b{b :0{width}b}
= 0b{(a ^ b) & mask :0{width}b}
NOT: ~ 0b{a :0{width}b}
= 0b{(~a) & mask :0{width}b}
SHIFTS
RIGHT: 0b{a :0{width}b} >> 1
= 0b{(a >> 1) & mask :0{width}b}
LEFT: 0b{a :0{width}b} << 1
= 0b{(a << 1) & mask :0{width}b}
""")
 
def rotr(width, a, n):
# Requires quite a stretch of the imagination to call this "native" support of right rotate, but it works
"Rotate a, n times to the right"
[System.Security.Cryptography.SHA256Managed].GetMethod('RotateRight', 'NonPublic, Static', $null, @([UInt32], [Int32]), $null).Invoke($null, @([uint32]$X, $Y))</lang>
if n < 0:
return rotl(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n % width
return ((a >> n) # top moved down
| ((a & ((1 << n) - 1)) # Bottom masked...
<< (width - n))) # ... then moved up
 
def rotl(width, a, n):
=={{header|Python}}==
"Rotate a, n times to the left"
<lang python>def bitwise(a, b):
if n < 0:
return rotr(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n % width
return (((a << n) & mask) # bottom shifted up and masked
| (a >> (width - n))) # Top moved down
def asr(width, a, n):
"Arithmetic shift a, n times to the right. (sign preserving)."
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
if n < 0:
return (a << -n) & mask
elif n == 0:
return a
elif n >= width:
return mask if a & top_bit_mask else 0
else:
a = a & mask
if a & top_bit_mask: # Sign bit set?
signs = (1 << n) - 1
return a >> n | (signs << width - n)
else:
return a >> n
def helper_funcs(width, a):
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
aa = a | top_bit_mask # a with top bit set
print(f"""\
ROTATIONS
RIGHT: rotr({width}, 0b{a :0{width}b}, 1)
= 0b{rotr(width, a, 1) :0{width}b}
rotr({width}, 0b{a :0{width}b}, 2)
= 0b{rotr(width, a, 2) :0{width}b}
rotr({width}, 0b{a :0{width}b}, 4)
= 0b{rotr(width, a, 4) :0{width}b}
LEFT: rotl({width}, 0b{a :0{width}b}, 1)
= 0b{rotl(width, a, 1) :0{width}b}
rotl({width}, 0b{a :0{width}b}, 2)
= 0b{rotl(width, a, 2) :0{width}b}
rotl({width}, 0b{a :0{width}b}, 4)
= 0b{rotl(width, a, 4) :0{width}b}
SIGN-EXTENDING ARITHMETIC SHIFT RIGHT
asr({width}, 0b{a :0{width}b}, 1)
= 0b{asr(width, a, 1) :0{width}b}
asr({width}, 0b{aa :0{width}b}, 1)
= 0b{asr(width, aa, 1) :0{width}b}
asr({width}, 0b{a :0{width}b}, 2)
= 0b{asr(width, a, 2) :0{width}b}
asr({width}, 0b{aa :0{width}b}, 2)
= 0b{asr(width, aa, 2) :0{width}b}
asr({width}, 0b{a :0{width}b}, 4)
= 0b{asr(width, a, 4) :0{width}b}
asr({width}, 0b{aa :0{width}b}, 4)
= 0b{asr(width, aa, 4) :0{width}b}
""")
 
if __name__ == '__main__':
bitwise_built_ins(8, 27, 125)
helper_funcs(8, 27)</syntaxhighlight>
 
{{out}}
<pre> AND: 0b00011011
& 0b01111101
= 0b00011001
OR: 0b00011011
| 0b01111101
= 0b01111111
XOR: 0b00011011
^ 0b01111101
= 0b01100110
NOT: ~ 0b00011011
= 0b11100100
SHIFTS
RIGHT: 0b00011011 >> 1
= 0b00001101
LEFT: 0b00011011 << 1
= 0b00110110
 
ROTATIONS
RIGHT: rotr(8, 0b00011011, 1)
= 0b10001101
rotr(8, 0b00011011, 2)
= 0b11000110
rotr(8, 0b00011011, 4)
= 0b10110001
LEFT: rotl(8, 0b00011011, 1)
= 0b00110110
rotl(8, 0b00011011, 2)
= 0b01101100
rotl(8, 0b00011011, 4)
= 0b10110001
SIGN-EXTENDING ARITHMETIC SHIFT RIGHT
asr(8, 0b00011011, 1)
= 0b00001101
asr(8, 0b10011011, 1)
= 0b11001101
asr(8, 0b00011011, 2)
= 0b00000110
asr(8, 0b10011011, 2)
= 0b11100110
asr(8, 0b00011011, 4)
= 0b00000001
asr(8, 0b10011011, 4)
= 0b11111001 </pre>
 
===Python 2===
<syntaxhighlight lang="python">def bitwise(a, b):
print 'a and b:', a & b
print 'a or b:', a | b
Line 2,237 ⟶ 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 2,243 ⟶ 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 2,250 ⟶ 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 2,294 ⟶ 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>.
 
<syntaxhighlight lang="quackery"> [ [] swap
64 times
[ 2 /mod
number$ rot join swap ]
drop
echo$ cr ] is echobin ( n --> )
 
[ 64 swap - rot64 ] is rrot64 ( n --> n )
 
[ say "first integer: " over echobin
say "second integer: " dup echobin
say "bitwise AND: " 2dup & echobin
say "bitwise OR: " 2dup | echobin
say "bitwise XOR: " 2dup ^ echobin
say "bitwise NOT: " over ~ echobin
say "bitwise LSHIFT: " 2dup << echobin
say "bitwise RSHIFT: " 2dup >> echobin
say "bitwise LROTATE: " 2dup rot64 echobin
say "bitwise RROTATE: " rrot64 echobin ] is task ( n n --> )
 
hex FFFFF hex F task</syntaxhighlight>
 
{{out}}
 
<pre>first integer: 0000000000000000000000000000000000000000000011111111111111111111
second integer: 0000000000000000000000000000000000000000000000000000000000001111
bitwise AND: 0000000000000000000000000000000000000000000000000000000000001111
bitwise OR: 0000000000000000000000000000000000000000000011111111111111111111
bitwise XOR: 0000000000000000000000000000000000000000000011111111111111110000
bitwise NOT: 1111111111111111111111111111111111111111111100000000000000000000
bitwise LSHIFT: 0000000000000000000000000000011111111111111111111000000000000000
bitwise RSHIFT: 0000000000000000000000000000000000000000000000000000000000011111
bitwise LROTATE: 0000000000000000000000000000011111111111111111111000000000000000
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 2,310 ⟶ 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 2,335 ⟶ 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 2,345 ⟶ 5,418:
bitShiftL(35, 1) # 70
bitShiftR(35, 1) # 17
# Note that no bit rotation is provided in this package</langsyntaxhighlight>
 
===Using hidden native functions from ''base'' package===
<lang r># As one can see from
getDLLRegisteredRoutines(getLoadedDLLs()$base)
# R knows functions bitwiseAnd, bitwiseOr, bitwiseXor and bitwiseNot.
# Here is how to call them (see ?.Call for the calling mechanism):
 
.Call("bitwiseOr", as.integer(12), as.integer(10))
.Call("bitwiseXor", as.integer(12), as.integer(10))
.Call("bitwiseAnd", as.integer(12), as.integer(10))
.Call("bitwiseNot", as.integer(12))
 
# It would be easy to embed these calls in R functions, for better readability
# Also, it's possible to call these functions on integer vectors:
 
.Call("bitwiseOr", c(5L, 2L), c(3L, 8L))</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define a 255)
Line 2,374 ⟶ 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" line>constant MAXINT = uint.Range.max;
constant BITS = MAXINT.base(2).chars;
 
# define rotate ops for the fun of it
multi sub infix:<⥁>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).list.rotate(b).reverse] }
multi sub infix:<⥀>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).reverse.list.rotate(b)] }
 
sub int-bits (Int $a, Int $b) {
say '';
say_bit "$a", $a;
say '';
say_bit "2's complement $a", +^$a;
say_bit "$a and $b", $a +& $b;
say_bit "$a or $b", $a +| $b;
say_bit "$a xor $b", $a +^ $b;
say_bit "$a unsigned shift right $b", ($a +& MAXINT) +> $b;
say_bit "$a signed shift right $b", $a +> $b;
say_bit "$a rotate right $b", $a ⥁ $b;
say_bit "$a shift left $b", $a +< $b;
say_bit "$a rotate left $b", $a ⥀ $b;
}
 
int-bits(7,2);
int-bits(-65432,31);
 
sub say_bit ($message, $value) {
printf("%30s: %{'0' ~ BITS}b\n", $message, $value +& MAXINT);
}</syntaxhighlight>
{{out}}
<pre> 7: 0000000000000000000000000000000000000000000000000000000000000111
 
2's complement 7: 1111111111111111111111111111111111111111111111111111111111111000
7 and 2: 0000000000000000000000000000000000000000000000000000000000000010
7 or 2: 0000000000000000000000000000000000000000000000000000000000000111
7 xor 2: 0000000000000000000000000000000000000000000000000000000000000101
7 unsigned shift right 2: 0000000000000000000000000000000000000000000000000000000000000001
7 signed shift right 2: 0000000000000000000000000000000000000000000000000000000000000001
7 rotate right 2: 1100000000000000000000000000000000000000000000000000000000000001
7 shift left 2: 0000000000000000000000000000000000000000000000000000000000011100
7 rotate left 2: 0000000000000000000000000000000000000000000000000000000000011100
 
-65432: 1111111111111111111111111111111111111111111111110000000001101000
 
2's complement -65432: 0000000000000000000000000000000000000000000000001111111110010111
-65432 and 31: 0000000000000000000000000000000000000000000000000000000000001000
-65432 or 31: 1111111111111111111111111111111111111111111111110000000001111111
-65432 xor 31: 1111111111111111111111111111111111111111111111110000000001110111
-65432 unsigned shift right 31: 0000000000000000000000000000000111111111111111111111111111111111
-65432 signed shift right 31: 1111111111111111111111111111111111111111111111111111111111111111
-65432 rotate right 31: 1111111111111110000000001101000111111111111111111111111111111111
-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
b: 2
 
print [
pad "a =" 10 a newline
pad "b =" 10 b newline
pad "a AND b:" 10 a and b newline
pad "a OR b:" 10 a or b newline
pad "a XOR b:" 10 a xor b newline
pad "NOT a:" 10 complement a newline
pad "a >>> b:" 10 a >>> b newline
pad "a >> b:" 10 a >> b newline
pad "a << b:" 10 a << b newline
; there are no circular shift operators in Red
]
</syntaxhighlight>
{{out}}
<pre>
a = 10
b = 2
a AND b: 2
a OR b: 10
a XOR b: 8
NOT a: -11
a >>> b: 2
a >> b: 2
a << b: 40
</pre>
=={{header|Retro}}==
There is no predefined arithmetic shifts in Retro.
 
<syntaxhighlight lang="retro">
<lang Retro>
: bitwise ( ab- )
cr
Line 2,394 ⟶ 5,535:
2over << "a << b = %d\n" puts
2over >> "a >> b = %d\n" puts
2drop ;</langsyntaxhighlight>
 
=={{header|REXX}}==
<pre>
<lang rexx>/*REXX program performs bitwise operations on integers: & | && ¬ «L »R */
╔═══════════════════════════════════════════════════════════════════════════════════════╗
numeric digits 1000 /*be able to handle big integers.*/
║ Since REXX stores numbers (indeed, all values) as characters, it makes no sense to ║
 
║ "rotate" a value, since there aren't any boundaries for the value. I.E.: there ║
say center('decimal',9) center("value",9) center('bits',50)
║ isn't any 32─bit word "container" or "cell" (for instance) to store an integer. ║
say copies('─',9) copies('─',9) copies('─',50)
║ ║
 
║ Furthermore, since REXX numbers can be arbitrary precision, the concept of rotating ║
a = 21 ; call show a , 'A' /* show & tell A */
b =a number 3has no ;meaning. call show b , 'B' /* show & tell B */
╚═══════════════════════════════════════════════════════════════════════════════════════╝
 
</pre>
call show bAnd(a,b) , 'A & B' /* and */
<syntaxhighlight lang="rexx">/*REXX program performs bit─wise operations on integers: & call show bOr( a,b) , 'A | B' && /* or ¬ «L »R */
numeric digits 1000 call show bXOr(a,b) , 'A && B' /*be able xor to handle ginormous integers.*/
say call show bNotcenter(a) , '¬ Adecimal', 9) center("value", /*9) not center('bits', */50)
say copies('─' call show bShiftL(a,b 9) , 'A [«B]' copies("─" /* shift, 9) left */ copies('─', 50)
a = 21 ; call show call show bShiftR(a,b) , 'A [»B]' /* shirtdisplay right A */
b = 3 ; call show b , 'B' /* display B */
/*┌───────────────────────────────────────────────────────────────┐
call show bAnd(a, b) , 'A & B' /* and */
│ Since REXX stores numbers (indeed, all values) as characters, │
call show bOr(a, b) , 'A | B' /* or */
│ it makes no sense to "rotate" a value, since there aren't any │
call show bXor(a, b) , 'A && B' /* xor */
│ boundries for the value. I.E.: there isn't any 32─bit word │
call show bNot(a) , '¬ A' /* not */
│ "container" or "cell" (for instance) to store an integer. │
call show bShiftL(a, b) , 'A [«B]' /* shift left */
└───────────────────────────────────────────────────────────────┘*/
exit call show bShiftR(a, b) , 'A [»B]' /*stick ashirt forkright in it, we're done.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────subroutines─────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: procedure; parse arg x,t; say right(x,9) center(t,9) right(d2b(x),50); return
d2bshow: say return x2b(d2xright( arg(1), 9) center( arg(2), +09) right( d2b( /*somearg(1) REXXes), have50); the D2B bif.*/return
b2dd2b: return x2dx2b(b2x d2x( arg(1) ) ) + 0 /*some REXXes have the B2D D2B bif BIF. */
bNotb2d: return b2dx2d(translate(d2b b2x( arg(1) ), 10, 01)) +0 /*+0≡normalize. " " " " B2D " */
bShiftLbNot: return (b2d( translate( d2b( arg(1)) ||), copies(010, arg(2))01) ) +0 /*+0 ≡ normalizes a #.*/
bShiftL: return b2d( d2b( arg(1) ) || copies(0, arg(2) ) ) +0 /* " " " " " */
bAnd: procedure; parse arg x,y; return c2d(bitand(d2c(x), d2c(y)))
bOrbAnd: procedure; parse arg x,y; return c2d(bitor bitand( d2c(x arg(1) ), d2c(y arg(2) ) ) )
bXorbOr: procedure; parse arg x,y; return c2d(bitxor bitor( d2c(x arg(1) ), d2c(y arg(2) ) ) )
bXor: return c2d( bitxor( d2c( arg(1) ), d2c( arg(2) ) ) )
 
bShiftR: procedure; parse arg x,y; $=substr(reverse(d2b(xarg(1))), yarg(2)+1); if $='' then $=0; return b2d(reverse($))</syntaxhighlight>
{{out|output}}
if $=='' then $=0; return b2d(reverse($))</lang>
'''output'''
<pre>
decimal value bits
Line 2,444 ⟶ 5,583:
2 A [»B] 10
</pre>
=={{header|Ring}}==
<syntaxhighlight lang="ring">
x = 8
y = 2
 
see "x & y - Binary AND : " + (x & y) + nl
see "x | y - Binary OR : " + (x | y) + nl
see "x ^ y - Binary XOR : " + (x ^ y) +nl
see "~x - Binary Ones Complement : " + (~x) + nl
see "x << y - Binary Left Shift : " + (x << y) + nl
see "x >> y - Binary Right Shift : " + (x >> y) + nl
</syntaxhighlight>
=={{header|RLaB}}==
 
Line 2,450 ⟶ 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 2,462 ⟶ 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}}==
<syntaxhighlight lang="robotic">
input string "First value"
set "local1" to "input"
input string "Second value"
set "local2" to "input"
 
. ">>> is an arithmetic shift; >> is a logical shift"
[ "a AND b = ('local1' a 'local2')"
[ "a OR b = ('local1' o 'local2')"
[ "a XOR b = ('local1' x 'local2')"
[ "NOT a = (~'local1')"
[ "a << b = ('local1' << 'local2')"
[ "a >> b = ('local1' >> 'local2')"
[ "a >>> b = ('local1' >>> 'local2')"
end
. "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}}==
<langsyntaxhighlight lang="ruby">def bitwise(a, b)
form = "%1$7s:%2$6d %2$016b"
puts form % ["a", a]
Line 2,477 ⟶ 5,666:
end
 
bitwise(14,3)</langsyntaxhighlight>
 
{{out}}
Line 2,492 ⟶ 5,681:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
let a: u8 = 105;
let b: u8 = 91;
Line 2,503 ⟶ 5,692:
println!("a << 3 = {:0>8b}", a << 3);
println!("a >> 3 = {:0>8b}", a >> 3);
}</langsyntaxhighlight>
 
Output:
Line 2,517 ⟶ 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 2,530 ⟶ 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 2,545 ⟶ 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 2,563 ⟶ 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 2,581 ⟶ 5,792:
Right shifting of bin32 values is done with logical shifts.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bin32.s7i";
 
Line 2,610 ⟶ 5,821:
bitwise(65076, 6);
bitwise(bin32(65076), bin32(6));
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,629 ⟶ 5,840:
a rolR b: 11010000000000000000001111111000
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func bitwise(a, b) {
say ('a and b : ', a & b)
 
#say Make('a sureor theyb are integers: ', a | b)
say ('a xor b : ', a ^ b)
a.to_int!;
say ('not a : ', ~a)
b.to_int!;
say ('a << b : ', a << b) # left shift
 
say ('a and>> b : ', a &>> b); # arithmetic right shift
say ('a or b : ', a | b);
say ('a xor b : ', a ^ b);
say ('not a : ', ~a);
say ('a << b : ', a << b); # left shift
say ('a >> b : ', a >> b); # arithmetic right shift
}
 
bitwise(14,3)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,655 ⟶ 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;
WORDSIZE := 32;
BEGIN
 
PROCEDURE TOBITS(N,B); INTEGER N; BOOLEAN ARRAY B;
BEGIN
INTEGER I,BITN;
FOR I := WORDSIZE-1 STEP -1 UNTIL 0 DO BEGIN
BITN := MOD(N,2); B(I) := BITN<>0; N := N // 2;
END;
END TOBITS;
 
INTEGER PROCEDURE FROMBITS(B); BOOLEAN ARRAY B;
BEGIN
INTEGER I, RESULT;
FOR I := 0 STEP 1 UNTIL WORDSIZE-1 DO
RESULT := 2 * RESULT + (IF B(I) THEN 1 ELSE 0);
FROMBITS := RESULT;
END FROMBITS;
 
INTEGER PROCEDURE BITOP(A,B,F);
INTEGER A,B;
PROCEDURE F IS BOOLEAN PROCEDURE F(A,B); BOOLEAN A,B;;
BEGIN
INTEGER I;
BOOLEAN ARRAY BA(0:WORDSIZE-1);
BOOLEAN ARRAY BB(0:WORDSIZE-1);
TOBITS(A,BA);
TOBITS(B,BB);
FOR I := 0 STEP 1 UNTIL WORDSIZE-1 DO BA(I) := F(BA(I),BB(I));
BITOP := FROMBITS(BA);
END BITOP;
 
INTEGER PROCEDURE BITUOP(A,F);
INTEGER A;
PROCEDURE F IS BOOLEAN PROCEDURE F(A); BOOLEAN A;;
BEGIN
INTEGER I;
BOOLEAN ARRAY BA(0:WORDSIZE-1);
TOBITS(A,BA);
FOR I := 0 STEP 1 UNTIL WORDSIZE-1 DO BA(I) := F(BA(I));
BITUOP := FROMBITS(BA);
END BITUOP;
 
BOOLEAN PROCEDURE OPAND(A,B); BOOLEAN A,B; OPAND := A AND B;
INTEGER PROCEDURE BITAND(A,B); INTEGER A,B; BITAND := BITOP(A,B,OPAND);
 
BOOLEAN PROCEDURE OPOR(A,B); BOOLEAN A,B; OPOR := A OR B;
INTEGER PROCEDURE BITOR(A,B); INTEGER A,B; BITOR := BITOP(A,B,OPOR);
 
BOOLEAN PROCEDURE OPXOR(A,B); BOOLEAN A,B; OPXOR := (A AND NOT B) OR (NOT A AND B);
INTEGER PROCEDURE BITXOR(A,B); INTEGER A,B; BITXOR := BITOP(A,B,OPXOR);
 
BOOLEAN PROCEDURE OPNOT(A); BOOLEAN A; OPNOT := NOT A;
INTEGER PROCEDURE BITNOT(A); INTEGER A; BITNOT := BITUOP(A,OPNOT);
 
INTEGER PROCEDURE BITSHL(A,B); INTEGER A,B;
BEGIN
IF B < 0 THEN A := BITSHR(A,-B)
ELSE WHILE B > 0 DO BEGIN A := 2 * A; B := B-1; END;
BITSHL := A;
END BITSHL;
 
INTEGER PROCEDURE BITSHR(A,B); INTEGER A,B;
BEGIN
IF B < 0 THEN A := BITSHL(A,-B)
ELSE WHILE B > 0 DO BEGIN A := A // 2; B := B-1; END;
BITSHR := A;
END BITSHR;
 
INTEGER PROCEDURE BITROTR(A,B); INTEGER A,B;
BEGIN
INTEGER I,J;
BOOLEAN ARRAY BA(0:WORDSIZE-1);
BOOLEAN ARRAY BB(0:WORDSIZE-1);
TOBITS(A,BA);
FOR I := 0 STEP 1 UNTIL WORDSIZE-1 DO BEGIN
J := MOD(I + B, WORDSIZE); BB(J) := BA(I);
END;
BITROTR := FROMBITS(BB);
END BITROTR;
 
INTEGER PROCEDURE BITROTL(A,B); INTEGER A,B;
BITROTL := BITROTR(A,-B);
 
PROCEDURE BITWISE(A,B); INTEGER A,B;
BEGIN
OUTTEXT("A AND B : "); OUTINT(BITAND(A,B),0); OUTIMAGE;
OUTTEXT("A OR B : "); OUTINT(BITOR (A,B),0); OUTIMAGE;
OUTTEXT("A XOR B : "); OUTINT(BITXOR(A,B),0); OUTIMAGE;
OUTTEXT("NOT A : "); OUTINT(BITNOT(A), 0); OUTIMAGE;
OUTTEXT("A << B : "); OUTINT(BITSHL(A,B),0); OUTIMAGE; ! LEFT SHIFT ;
OUTTEXT("A >> B : "); OUTINT(BITSHR(A,B),0); OUTIMAGE; ! ARITHMETIC RIGHT SHIFT ;
OUTTEXT("A ROTL B : "); OUTINT(BITROTL(A,B),0); OUTIMAGE; ! ROTATE LEFT ;
OUTTEXT("A ROTR B : "); OUTINT(BITROTR(A,B),0); OUTIMAGE; ! ROTATE RIGHT ;
END BITWISE;
BITWISE(14,3);
END;
END
</syntaxhighlight>
{{out}}
<pre>A AND B : 2
A OR B : 15
A XOR B : 13
NOT A : -15
A << B : 112
A >> B : 1
A ROTL B : 112
A ROTR B : -1073741823
</pre>
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">[ |:a :b |
 
inform: (a bitAnd: b) printString.
Line 2,666 ⟶ 5,984:
inform: (a >> b) printString.
 
] applyTo: {8. 12}.</langsyntaxhighlight>
'''Bold text'''
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
Line 2,674 ⟶ 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 2,683 ⟶ 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 2,694 ⟶ 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 2,707 ⟶ 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 2,717 ⟶ 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 2,734 ⟶ 6,088:
}
 
bitwise(-15,3)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,745 ⟶ 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 2,767 ⟶ 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 2,782 ⟶ 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.
<syntaxhighlight lang="tailspin">
def a: [x f075 x];
def b: [x 81 x];
 
($a and $b) -> '$a; and $b; is $;$#10;' -> !OUT::write
($a or $b) -> '$a; or $b; is $;$#10;' -> !OUT::write
($a xor $b) -> '$a; xor $b; is $;$#10;' -> !OUT::write
$a::inverse -> 'not $a; is $;$#10;' -> !OUT::write
$a::shift&{left: 3, fill: [x 00 x]} -> '$a; shifted left 3 bits is $;$#10;' -> !OUT::write
$a::shift&{left: -3, fill: [x 00 x]} -> '$a; shifted right 3 bits is $;$#10;' -> !OUT::write
$a::shift&{left: -3, fill: $a(0)} -> '$a; arithmetically shifted right 3 bits is $;$#10;' -> !OUT::write
$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>
{{out}}
<pre>
f075 and 81 is f001
f075 or 81 is fff5
f075 xor 81 is 0ff4
not f075 is 0f8a
f075 shifted left 3 bits is 83a8
f075 shifted right 3 bits is 1e0e
f075 arithmetically shifted right 3 bits is fe0e
f075 rotated left 3 bits is 83af
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 2,794 ⟶ 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 2,808 ⟶ 6,188:
(($a >> (32-$b)) & ($bits ^ ($bits << $b)))
}]]
}</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
Line 2,816 ⟶ 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 2,838 ⟶ 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}}==
<syntaxhighlight lang="vala">void testbit(int a, int b) {
print(@"input: a = $a, b = $b\n");
print(@"AND: $a & $b = $(a & b)\n");
print(@"OR: $a | $b = $(a | b)\n");
print(@"XOR: $a ^ $b = $(a ^ b)\n");
print(@"LSH: $a << $b = $(a << b)\n");
print(@"RSH: $a >> $b = $(a >> b)\n");
print(@"NOT: ~$a = $(~a)\n");
/* there are no rotation operators in vala, but you could define your own
function to do what is required. */
}
 
void main() {
int a = 255;
int b = 2;
testbit(a,b);
}</syntaxhighlight>
{{out}}
<pre>input: a = 255, b = 2
AND: 255 & 2 = 2
OR: 255 | 2 = 255
XOR: 255 ^ 2 = 253
LSH: 255 << 2 = 1020
RSH: 255 >> 2 = 63
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
Debug.Print Hex(Not &HF0F0) 'F0F
Debug.Print Hex(&HF0F0 Eqv &HFF00) 'F00F
Debug.Print Hex(&HF0F0 Imp &HFF00) 'FF0F
</syntaxhighlight>
 
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
ElseIf k > 31 Then
MaskL = -1
Else
MaskL = (-1) Xor (2 ^ (32 - k) - 1)
End If
End Function
Function MaskR(k As Integer) As Long
If k < 1 Then
MaskR = 0
ElseIf k > 31 Then
MaskR = -1
Else
MaskR = 2 ^ k - 1
End If
End Function
Function Bit(k As Integer) As Long
If k < 0 Or k > 31 Then
Bit = 0
ElseIf k = 31 Then
Bit = MaskL(1)
Else
Bit = 2 ^ k
End If
End Function
Function ShiftL(n As Long, k As Integer) As Long
If k = 0 Then
ShiftL = n
ElseIf k > 31 Then
ShiftL = 0
ElseIf k < 0 Then
ShiftL = ShiftR(n, -k)
Else
ShiftL = (n And MaskR(31 - k)) * 2 ^ k
If (n And Bit(31 - k)) <> 0 Then ShiftL = ShiftL Or MaskL(1)
End If
End Function
Function ShiftR(n As Long, k As Integer) As Long
If k = 0 Then
ShiftR = n
ElseIf k > 31 Then
ShiftR = 0
ElseIf k < 0 Then
ShiftR = ShiftL(n, -k)
Else
ShiftR = (n And MaskR(31)) \ 2 ^ k
If (n And MaskL(1)) <> 0 Then ShiftR = ShiftR Or Bit(31 - k)
End If
End Function
Function RotateL(n As Long, k As Integer) As Long
k = (32768 + k) Mod 32
If k = 0 Then
RotateL = n
Else
RotateL = ShiftL(n, k) Or ShiftR(n, 32 - k)
End If
End Function
Function RotateR(n As Long, k As Integer) As Long
k = (32768 + k) Mod 32
If k = 0 Then
RotateR = n
Else
RotateR = ShiftR(n, k) Or ShiftL(n, 32 - k)
End If
End Function
Function ClearBit(n As Long, k As Integer) As Long
ClearBit = n And Not Bit(k)
End Function
Function SetBit(n As Long, k As Integer) As Long
SetBit = n Or Bit(k)
End Function
Function SwitchBit(n As Long, k As Integer) As Long
SwitchBit = n Xor Bit(k)
End Function
Function TestBit(n As Long, k As Integer) As Boolean
TestBit = (n And Bit(k)) <> 0
End Function</syntaxhighlight>
 
Examples
 
<syntaxhighlight lang="vb">Debug.Print Hex(MaskL(8)) 'FF000000
Debug.Print Hex(MaskR(8)) 'FF
Debug.Print Hex(Bit(7)) '80
Debug.Print Hex(ShiftL(-1, 8)) 'FFFFFF00
Debug.Print Hex(ShiftL(-1, -8)) 'FFFFFF
Debug.Print Hex(ShiftR(-1, 8)) 'FFFFFF
Debug.Print Hex(ShiftR(-1, -8)) 'FFFFFF00
Debug.Print Hex(RotateL(65535, 8)) 'FFFF00
Debug.Print Hex(RotateL(65535, -8)) 'FF0000FF
Debug.Print Hex(RotateR(65535, 8)) 'FF0000FF
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}}==
<langsyntaxhighlight lang="vbnet">Sub Test(a as Integer, b as Integer)
WriteLine("And " & a And b)
WriteLine("Or " & a Or b)
Line 2,848 ⟶ 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.
 
Although the same bitwise operators are supported as in C, the operands are converted to unsigned 32-bit integers before the operation is performed and return values of this form.
 
Consequently, it is not usually a good idea to try and perform bitwise operations on integer values outside this range or on non-integral values.
 
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="wren">var rl = Fn.new { |x, y| x << y | x >> (32-y) }
 
var rr = Fn.new { |x, y| x >> y | x << (32-y) }
 
var bitwise = Fn.new { |x, y|
if (!x.isInteger || !y.isInteger || x < 0 || y < 0 || x > 0xffffffff || y > 0xffffffff) {
Fiber.abort("Operands must be in the range of a 32-bit unsigned integer")
}
System.print(" x = %(x)")
System.print(" y = %(y)")
System.print(" x & y = %(x & y)")
System.print(" x | y = %(x | y)")
System.print(" x ^ y = %(x ^ y)")
System.print("~x = %(~x)")
System.print(" x << y = %(x << y)")
System.print(" x >> y = %(x >> y)")
System.print(" x rl y = %(rl.call(x, y))")
System.print(" x rr y = %(rr.call(x, y))")
}
 
bitwise.call(10, 2)</syntaxhighlight>
 
{{out}}
<pre>
x = 10
y = 2
x & y = 2
x | y = 10
x ^ y = 8
~x = 4294967285
x << y = 40
x >> y = 2
x rl y = 40
x rr y = 2147483650
</pre>
 
=={{header|x86 Assembly}}==
{{works with|nasm}}
It must be linked with the libc and "start" code; lazyly a <tt>gcc bitops.o</tt> works, being bitops.o produced by <tt>nasm -f elf bitops.asm</tt> (I've chosen ELF since I am on a GNU/Linux box)
<langsyntaxhighlight lang="asm"> extern printf
global main
Line 2,958 ⟶ 6,598:
_null db 0
 
end</langsyntaxhighlight>
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "bitwise"
 
DECLARE FUNCTION Entry()
INTERNAL FUNCTION ULONG Rotr(ULONG x, ULONG s)
 
FUNCTION Entry()
SLONG a, b
ULONG ua, ub
a = 21
b = 3
ua = a
ub = b
PRINT
PRINT "= Decimal ="
PRINT LTRIM$(STR$(a)); " AND"; b; ":"; a & b ' also: a AND b
PRINT LTRIM$(STR$(a)); " OR"; b; ":"; a | b ' also: a OR b
PRINT LTRIM$(STR$(a)); " XOR"; b; ":"; a ^ b' also: a XOR b
PRINT "NOT"; a; ":"; ~a ' also: NOT a
PRINT LTRIM$(STR$(a)); " <<<"; b; ":"; a <<< b ' arithmetic left shift
PRINT LTRIM$(STR$(a)); " >>>"; b; ":"; a >>> b ' arithmetic right shift
PRINT LTRIM$(STR$(ua)); " <<"; b; ":"; ua << b ' bitwise left shift
PRINT LTRIM$(STR$(ua)); " >>"; b; ":"; ua >> b ' bitwise right shift
PRINT LTRIM$(STR$(ua)); " rotr"; ub; ":"; Rotr(ua, ub)
PRINT
PRINT "= Binary ="
PRINT BIN$(a); " AND "; BIN$(b); ": "; BIN$(a & b)
PRINT BIN$(a); " OR "; BIN$(b); ": "; BIN$(a | b)
PRINT BIN$(a); " XOR "; BIN$(b); ": "; BIN$(a ^ b)
PRINT "NOT "; BIN$(a); ": "; BIN$(~a)
PRINT BIN$(a); " <<< "; BIN$(b); ": "; BIN$(a <<< b)
PRINT BIN$(a); " >>> "; BIN$(b); ": "; BIN$(a >>> b)
PRINT BIN$(ua); " << "; BIN$(b); ": "; BIN$(ua << b)
PRINT BIN$(ua); " >> "; BIN$(b); ": "; BIN$(ua >> b)
PRINT BIN$(ua); " Rotr "; BIN$(ub); ": "; BIN$(Rotr(ua, ub))
END FUNCTION
 
' Rotate x to the right by s bits
FUNCTION ULONG Rotr(ULONG x, ULONG s)
RETURN (x >> s) | (x << (SIZE(ULONG) * 8 - s))
END FUNCTION
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
= Decimal =
21 AND 3: 1
21 OR 3: 23
21 XOR 3: 22
NOT 21:-22
21 <<< 3: 168
21 >>> 3: 2
21 << 3: 168
21 >> 3: 2
21 Rotr 3: 2684354562
 
= Binary =
10101 AND 11: 1
10101 OR 11: 10111
10101 XOR 11: 10110
NOT 10101: 11111111111111111111111111101010
10101 <<< 11: 10101000
10101 >>> 11: 10
10101 << 11: 10101000
10101 >> 11: 10
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)))
(print `(,a or ,b = ,(logior a b)))
(print `(,a xor ,b = ,(logxor a b)))
(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)))) )</syntaxhighlight>
=={{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 2,971 ⟶ 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}}==
<syntaxhighlight lang="yabasic">sub formBin$(n)
return right$("00000000" + bin$(n), 8)
end sub
 
a = 6 : b = 3
print a, " = \t", formBin$(a)
print b, " = \t", formBin$(b)
print "\t--------"
print "AND = \t", formBin$(and(a, b))
print "OR = \t", formBin$(or(a, b))
print "XOR = \t", formBin$(xor(a, b))
print "NOT ", a, " =\t", formBin$(xor(255, a))</syntaxhighlight>
<pre>6 = 00000110
3 = 00000011
--------
AND = 00000010
OR = 00000111
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 2,986 ⟶ 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,458

edits