Bitwise operations: Difference between revisions
Content added Content deleted
m (→{{header|Phix}}: replaced (inline assembly version) with a js-compatible version) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 12: | Line 12: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
< |
<syntaxhighlight lang=11l>V x = 10 |
||
V y = 2 |
V y = 2 |
||
print(‘x = ’x) |
print(‘x = ’x) |
||
Line 23: | Line 23: | ||
print(‘x SHR y = ’(x >> y)) |
print(‘x SHR y = ’(x >> y)) |
||
print(‘x ROL y = ’rotl(x, y)) |
print(‘x ROL y = ’rotl(x, y)) |
||
print(‘x ROR y = ’rotr(x, y))</ |
print(‘x ROR y = ’rotr(x, y))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 39: | Line 39: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang=360asm>* Bitwise operations 15/02/2017 |
||
BITWISE CSECT |
BITWISE CSECT |
||
USING BITWISE,R13 |
USING BITWISE,R13 |
||
Line 120: | Line 120: | ||
PG DS CL12 |
PG DS CL12 |
||
YREGS |
YREGS |
||
END BITWISE</ |
END BITWISE</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 138: | Line 138: | ||
Bitwise operations are done using the accumulator and an immediate constant (prefixed with #) or a value at a specified memory location (no #.) |
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</ |
STA temp ;temp equals 5 for the following</syntaxhighlight> |
||
;AND |
;AND |
||
< |
<syntaxhighlight lang=6502asm>LDA #$08 |
||
AND temp</ |
AND temp</syntaxhighlight> |
||
;OR |
;OR |
||
< |
<syntaxhighlight lang=6502asm>LDA #$08 |
||
ORA temp</ |
ORA temp</syntaxhighlight> |
||
;XOR |
;XOR |
||
< |
<syntaxhighlight lang=6502asm>LDA #$08 |
||
EOR temp</ |
EOR temp</syntaxhighlight> |
||
;NOT |
;NOT |
||
< |
<syntaxhighlight lang=6502asm>LDA #$08 |
||
EOR #255</ |
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. |
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 |
CLC ;clear the carry. That way, ROR will not accidentally shift a 1 into the top bit of a positive number |
||
BPL SKIP |
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. |
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: |
SKIP: |
||
ROR</ |
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. |
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.) |
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.</ |
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.</ |
ROR ;if the carry was set prior to the ROR, A = 0x80. If clear, A = 0.</syntaxhighlight> |
||
=={{header|68000 Assembly}}== |
=={{header|68000 Assembly}}== |
||
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation. |
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation. |
||
;AND |
;AND |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0 |
||
MOVE.W #$200,D1 |
MOVE.W #$200,D1 |
||
AND.W D0,D1</ |
AND.W D0,D1</syntaxhighlight> |
||
;OR |
;OR |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0 |
||
MOVE.W #$200,D1 |
MOVE.W #$200,D1 |
||
OR.W D0,D1</ |
OR.W D0,D1</syntaxhighlight> |
||
;XOR |
;XOR |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0 |
||
MOVE.W #$200,D1 |
MOVE.W #$200,D1 |
||
EOR.W D0,D1</ |
EOR.W D0,D1</syntaxhighlight> |
||
;NOT |
;NOT |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0 |
||
NOT.W D0</ |
NOT.W D0</syntaxhighlight> |
||
;Left Shift |
;Left Shift |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$FF,D0 |
||
MOVE.W #$04,D1 |
MOVE.W #$04,D1 |
||
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</ |
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</syntaxhighlight> |
||
;Right Shift |
;Right Shift |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$FF,D0 |
||
MOVE.W #$04,D1 |
MOVE.W #$04,D1 |
||
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</ |
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</syntaxhighlight> |
||
;Arithmetic Right Shift |
;Arithmetic Right Shift |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
||
MOVE.W #$04,D1 |
MOVE.W #$04,D1 |
||
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</ |
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</syntaxhighlight> |
||
;Left Rotate |
;Left Rotate |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
||
MOVE.W #$04,D1 |
MOVE.W #$04,D1 |
||
ROL.W D1,D0</ |
ROL.W D1,D0</syntaxhighlight> |
||
;Right Rotate |
;Right Rotate |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
||
MOVE.W #$04,D1 |
MOVE.W #$04,D1 |
||
ROR.W D1,D0</ |
ROR.W D1,D0</syntaxhighlight> |
||
;Left Rotate Through Extend Flag |
;Left Rotate Through Extend Flag |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
||
MOVE.W #$04,D1 |
MOVE.W #$04,D1 |
||
ROXL.W D1,D0</ |
ROXL.W D1,D0</syntaxhighlight> |
||
;Right Rotate Through Extend Flag |
;Right Rotate Through Extend Flag |
||
< |
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
||
MOVE.W #$04,D1 |
MOVE.W #$04,D1 |
||
ROXR.W D1,D0</ |
ROXR.W D1,D0</syntaxhighlight> |
||
=={{header|8051 Assembly}}== |
=={{header|8051 Assembly}}== |
||
Line 234: | Line 234: | ||
The end result of each operation resides in a. |
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. |
The shift and rotate operations should likely push psw and pop psw because they affect the carry flag. |
||
< |
<syntaxhighlight lang=asm>; bitwise AND |
||
anl a, b |
anl a, b |
||
Line 285: | Line 285: | ||
loop: |
loop: |
||
rr a |
rr a |
||
djnz b, loop</ |
djnz b, loop</syntaxhighlight> |
||
=={{header|8086 Assembly}}== |
=={{header|8086 Assembly}}== |
||
;AND |
;AND |
||
< |
<syntaxhighlight lang=asm>MOV AX,0345h |
||
MOV BX,0444h |
MOV BX,0444h |
||
AND AX,BX</ |
AND AX,BX</syntaxhighlight> |
||
;OR |
;OR |
||
< |
<syntaxhighlight lang=asm>MOV AX,0345h |
||
MOV BX,0444h |
MOV BX,0444h |
||
OR AX,BX</ |
OR AX,BX</syntaxhighlight> |
||
;XOR |
;XOR |
||
< |
<syntaxhighlight lang=asm>MOV AX,0345h |
||
MOV BX,0444h |
MOV BX,0444h |
||
XOR AX,BX</ |
XOR AX,BX</syntaxhighlight> |
||
;NOT |
;NOT |
||
< |
<syntaxhighlight lang=asm>MOV AX,0345h |
||
NOT AX</ |
NOT AX</syntaxhighlight> |
||
;Left Shift |
;Left Shift |
||
< |
<syntaxhighlight lang=asm>MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
SHL AX,CL</ |
SHL AX,CL</syntaxhighlight> |
||
;Right Shift |
;Right Shift |
||
< |
<syntaxhighlight lang=asm>MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
SHR AX,CL</ |
SHR AX,CL</syntaxhighlight> |
||
;Arithmetic Right Shift |
;Arithmetic Right Shift |
||
< |
<syntaxhighlight lang=asm>MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
SAR AX,CL</ |
SAR AX,CL</syntaxhighlight> |
||
;Left Rotate |
;Left Rotate |
||
< |
<syntaxhighlight lang=asm>MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
ROL AX,CL</ |
ROL AX,CL</syntaxhighlight> |
||
;Right Rotate |
;Right Rotate |
||
< |
<syntaxhighlight lang=asm>MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
ROR AX,CL</ |
ROR AX,CL</syntaxhighlight> |
||
;Left Rotate Through Carry |
;Left Rotate Through Carry |
||
< |
<syntaxhighlight lang=asm>MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
RCL AX,CL</ |
RCL AX,CL</syntaxhighlight> |
||
;Right Rotate Through Carry |
;Right Rotate Through Carry |
||
< |
<syntaxhighlight lang=asm>MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
RCR AX,CL</ |
RCR AX,CL</syntaxhighlight> |
||
=={{header|ABAP}}== |
=={{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. |
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. |
report z_bitwise_operations. |
||
Line 611: | Line 611: | ||
new_value = result ). |
new_value = result ). |
||
write: |a rotr b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /. |
write: |a rotr b -> { result }, { hex_converter=>to_binary( result ) }, { hex_converter=>to_decimal( result ) }|, /. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{output}} |
{{output}} |
||
Line 642: | Line 642: | ||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
Unlisted operations are not available |
Unlisted operations are not available |
||
< |
<syntaxhighlight lang=Lisp>(defun bitwise (a b) |
||
(list (logand a b) |
(list (logand a b) |
||
(logior a b) |
(logior a b) |
||
Line 648: | Line 648: | ||
(lognot a) |
(lognot a) |
||
(ash a b) |
(ash a b) |
||
(ash a (- b))))</ |
(ash a (- b))))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang=Action!>BYTE FUNC Not(BYTE a) |
||
RETURN (a!$FF) |
RETURN (a!$FF) |
||
Line 674: | Line 674: | ||
res=a LSH b |
res=a LSH b |
||
PrintF("%B SHL %B = %B%E",a,b,res) |
PrintF("%B SHL %B = %B%E",a,b,res) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bitwise_operations.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bitwise_operations.png Screenshot from Atari 8-bit computer] |
||
Line 688: | Line 688: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
ActionScript does not support bitwise rotations. |
ActionScript does not support bitwise rotations. |
||
< |
<syntaxhighlight lang=ActionScript>function bitwise(a:int, b:int):void |
||
{ |
{ |
||
trace("And: ", a & b); |
trace("And: ", a & b); |
||
Line 697: | Line 697: | ||
trace("Right Shift(Arithmetic): ", a >> b); |
trace("Right Shift(Arithmetic): ", a >> b); |
||
trace("Right Shift(Logical): ", a >>> b); |
trace("Right Shift(Logical): ", a >>> b); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
The following program performs all required operations and prints the resulting values in base 2 for easy checking of the bit values. |
The following program performs all required operations and prints the resulting values in base 2 for easy checking of the bit values. |
||
< |
<syntaxhighlight lang=ada>with Ada.Text_IO, Interfaces; |
||
use Ada.Text_IO, Interfaces; |
use Ada.Text_IO, Interfaces; |
||
Line 724: | Line 724: | ||
Put_Line (Unsigned_8'Image (Rotate_Left (X, N))); |
Put_Line (Unsigned_8'Image (Rotate_Left (X, N))); |
||
Put_Line (Unsigned_8'Image (Rotate_Right (X, N))); |
Put_Line (Unsigned_8'Image (Rotate_Right (X, N))); |
||
end Bitwise;</ |
end Bitwise;</syntaxhighlight> |
||
=={{header|Aikido}}== |
=={{header|Aikido}}== |
||
Line 730: | Line 730: | ||
There is no rotate support built in to Aikido. |
There is no rotate support built in to Aikido. |
||
< |
<syntaxhighlight lang=aikido>function bitwise(a, b){ |
||
println("a AND b: " + (a & b)) |
println("a AND b: " + (a & b)) |
||
println("a OR b: "+ (a | b)) |
println("a OR b: "+ (a | b)) |
||
Line 738: | Line 738: | ||
println("a >> b: " + (a >> b)) // arithmetic right shift |
println("a >> b: " + (a >> b)) // arithmetic right shift |
||
println("a >>> b: " + (a >>> b)) // logical right shift |
println("a >>> b: " + (a >>> b)) // logical right shift |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 747: | Line 747: | ||
* 2r00000000000000000000000010101010, 4r0000000000002222, 8r00000000252, 16r000000aa |
* 2r00000000000000000000000010101010, 4r0000000000002222, 8r00000000252, 16r000000aa |
||
* and as an array of BOOL: FFFFFFFFFFFFFFFFFFFFFFFFTFTFTFTF |
* and as an array of BOOL: FFFFFFFFFFFFFFFFFFFFFFFFTFTFTFTF |
||
< |
<syntaxhighlight lang=algol68>main:( |
||
PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here # |
PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here # |
||
Line 810: | Line 810: | ||
bitwise(16rff,16raa,5) |
bitwise(16rff,16raa,5) |
||
END CO |
END CO |
||
)</ |
)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> bits shorths: +1 1 plus the number of extra SHORT BITS types |
<pre> bits shorths: +1 1 plus the number of extra SHORT BITS types |
||
Line 836: | Line 836: | ||
</pre> |
</pre> |
||
Note that an INT can be widened into BITS, and BITS can be widened into an array of BOOL. eg: |
Note that an INT can be widened into BITS, and BITS can be widened into an array of BOOL. eg: |
||
< |
<syntaxhighlight lang=algol68># unpack (widen) some data back into an a BOOL array # |
||
INT i := 170; |
INT i := 170; |
||
BITS j := BIN i; |
BITS j := BIN i; |
||
Line 848: | Line 848: | ||
i := ABS j; |
i := ABS j; |
||
printf(($g", 8r"8r4d", "8(g)l$, i, j, k[bits width-8+1:]))</ |
printf(($g", 8r"8r4d", "8(g)l$, i, j, k[bits width-8+1:]))</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 856: | Line 856: | ||
=={{header|ALGOL W}}== |
=={{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 % |
% Algol W does not have xor, arithmetic right shift, left rotate or right rotate % |
||
procedure bitOperations ( integer value n1, n2 ) ; |
procedure bitOperations ( integer value n1, n2 ) ; |
||
Line 874: | Line 874: | ||
write( n1, " shl ", n2, " = ", number( b1 shl n2 ), " ( left-shift )" ); |
write( n1, " shl ", n2, " = ", number( b1 shl n2 ), " ( left-shift )" ); |
||
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" ) |
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" ) |
||
end bitOPerations ;</ |
end bitOPerations ;</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
Line 893: | Line 893: | ||
< |
<syntaxhighlight lang=applescript>use AppleScript version "2.4" |
||
use framework "Foundation" |
use framework "Foundation" |
||
use scripting additions |
use scripting additions |
||
Line 1,247: | Line 1,247: | ||
return lst |
return lst |
||
end tell |
end tell |
||
end zipWith</ |
end zipWith</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>32 bit signed integers (in two's complement binary encoding) |
<pre>32 bit signed integers (in two's complement binary encoding) |
||
Line 1,264: | Line 1,264: | ||
'''Second option''' – writing our own bitwise functions for Applescript: |
'''Second option''' – writing our own bitwise functions for Applescript: |
||
< |
<syntaxhighlight lang=applescript>use AppleScript version "2.4" |
||
use framework "Foundation" |
use framework "Foundation" |
||
use scripting additions |
use scripting additions |
||
Line 1,751: | Line 1,751: | ||
return lst |
return lst |
||
end tell |
end tell |
||
end zipWith</ |
end zipWith</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>32 bit signed integers (in two's complement binary encoding) |
<pre>32 bit signed integers (in two's complement binary encoding) |
||
Line 1,771: | Line 1,771: | ||
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. |
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 |
set out to 0 |
||
-- Multiplying equivalent bit values by each other gives 1 where they're both 1 and 0 otherwise. |
-- Multiplying equivalent bit values by each other gives 1 where they're both 1 and 0 otherwise. |
||
Line 1,852: | Line 1,852: | ||
leftRotate(92, 7, 8) --> 46 |
leftRotate(92, 7, 8) --> 46 |
||
rightRotate(92, 7, 8) --> 184 |
rightRotate(92, 7, 8) --> 184 |
||
rightRotate(92, 7, 16) --> 47104</ |
rightRotate(92, 7, 16) --> 47104</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
< |
<syntaxhighlight lang=ARM Assembly> |
||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
Line 2,018: | Line 2,018: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang=rebol>a: 255 |
||
b: 2 |
b: 2 |
||
Line 2,029: | Line 2,029: | ||
print ["NOT" a "=" not a] |
print ["NOT" a "=" not a] |
||
print [a "SHL" b "=" shl a b] |
print [a "SHL" b "=" shl a b] |
||
print [a "SHR" b "=" shr a b]</ |
print [a "SHR" b "=" shr a b]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,041: | Line 2,041: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang=AutoHotkey>bitwise(3, 4) |
||
bitwise(a, b) |
bitwise(a, b) |
||
{ |
{ |
||
Line 2,050: | Line 2,050: | ||
MsgBox % "a << b: " . a << b ; left shift |
MsgBox % "a << b: " . a << b ; left shift |
||
MsgBox % "a >> b: " . a >> b ; arithmetic right shift |
MsgBox % "a >> b: " . a >> b ; arithmetic right shift |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
No arithmetic shift. |
No arithmetic shift. |
||
< |
<syntaxhighlight lang=AutoIt>bitwise(255, 5) |
||
Func bitwise($a, $b) |
Func bitwise($a, $b) |
||
MsgBox(1, '', _ |
MsgBox(1, '', _ |
||
Line 2,065: | Line 2,065: | ||
$a & " ROL " & $b & ": " & BitRotate($a, $b) & @CRLF & _ |
$a & " ROL " & $b & ": " & BitRotate($a, $b) & @CRLF & _ |
||
$a & " ROR " & $b & ": " & BitRotate($a, $b * -1) & @CRLF ) |
$a & " ROR " & $b & ": " & BitRotate($a, $b * -1) & @CRLF ) |
||
EndFunc</ |
EndFunc</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,083: | Line 2,083: | ||
{{works with|gawk}} |
{{works with|gawk}} |
||
< |
<syntaxhighlight lang=awk>BEGIN { |
||
n = 11 |
n = 11 |
||
p = 1 |
p = 1 |
||
Line 2,092: | Line 2,092: | ||
print n " >> " p " = " rshift(n, p) # right shift |
print n " >> " p " = " rshift(n, p) # right shift |
||
printf "not %d = 0x%x\n", n, compl(n) # bitwise complement |
printf "not %d = 0x%x\n", n, compl(n) # bitwise complement |
||
}</ |
}</syntaxhighlight> |
||
[[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>. |
[[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}}== |
=={{header|Axe}}== |
||
< |
<syntaxhighlight lang=axe>Lbl BITS |
||
r₁→A |
r₁→A |
||
r₂→B |
r₂→B |
||
Line 2,105: | Line 2,105: | ||
Disp "NOT:",not(A)ʳ▶Dec,i |
Disp "NOT:",not(A)ʳ▶Dec,i |
||
.No language support for shifts or rotations |
.No language support for shifts or rotations |
||
Return</ |
Return</syntaxhighlight> |
||
Note that the symbols for AND, OR, and XOR are the stat plot marks near the bottom of the Catalog. |
Note that the symbols for AND, OR, and XOR are the stat plot marks near the bottom of the Catalog. |
||
Line 2,113: | Line 2,113: | ||
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. |
In Babel, we prefix the logic operators with a 'c' to denote that they are C-style operations, that is, they are word-width operations, not arbitrary size operations. The following program combines the numbers 5 and 9 using the various bitwise operators and then displays the results. |
||
< |
<syntaxhighlight lang=babel>({5 9}) ({cand} {cor} {cnor} {cxor} {cxnor} {shl} {shr} {ashr} {rol}) cart ! {give <- cp -> compose !} over ! {eval} over ! {;} each</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,128: | Line 2,128: | ||
The cnot operator works on just one operand: |
The cnot operator works on just one operand: |
||
<lang |
<syntaxhighlight lang=babel>9 cnot ;</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,136: | Line 2,136: | ||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
QuickBasic does not have shift or rotate operations defined. Here are the logical operations: |
QuickBasic does not have shift or rotate operations defined. Here are the logical operations: |
||
< |
<syntaxhighlight lang=qbasic>SUB bitwise (a, b) |
||
PRINT a AND b |
PRINT a AND b |
||
PRINT a OR b |
PRINT a OR b |
||
PRINT a XOR b |
PRINT a XOR b |
||
PRINT NOT a |
PRINT NOT a |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
{{works with|FreeBASIC}} |
{{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. |
FreeBASIC does not have rotate operators. Shift Right operator performs arithmetic shift if the left value is signed number and logical shift if the left value is unsigned number. |
||
< |
<syntaxhighlight lang=freebasic>SUB bitwise (a AS Integer, b AS Integer) |
||
DIM u AS UInteger |
DIM u AS UInteger |
||
Line 2,156: | Line 2,156: | ||
u = a |
u = a |
||
PRINT "a SHR b (logical) = "; u SHR b |
PRINT "a SHR b (logical) = "; u SHR b |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
==={{header|Commodore BASIC}}=== |
==={{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. |
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 |
20 INPUT "B="; B |
||
30 PRINT "A AND B =" A AND B :rem AND |
30 PRINT "A AND B =" A AND B :rem AND |
||
40 PRINT "A OR B =" A OR B :rem OR |
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 |
50 PRINT "A XOR B =" (A AND(NOT B))OR((NOT A)AND B) :rem XOR |
||
60 PRINT "NOT A =" NOT A :rem NOT</ |
60 PRINT "NOT A =" NOT A :rem NOT</syntaxhighlight> |
||
{{in}} |
{{in}} |
||
<pre>A=? 2 |
<pre>A=? 2 |
||
Line 2,178: | Line 2,178: | ||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang=IS-BASIC>100 LET A=10:LET B=12 |
||
110 PRINT A;"and";B;"=";A AND B |
110 PRINT A;"and";B;"=";A AND B |
||
120 PRINT A;"band";B;"=";A BAND B |
120 PRINT A;"band";B;"=";A BAND B |
||
Line 2,185: | Line 2,185: | ||
150 PRINT A;"xor";B;"=";XOR(A,B) |
150 PRINT A;"xor";B;"=";XOR(A,B) |
||
160 PRINT " not";A;"=";NOT A |
160 PRINT " not";A;"=";NOT A |
||
170 DEF XOR(A,B)=(A BOR B)-(A BAND B)</ |
170 DEF XOR(A,B)=(A BOR B)-(A BAND B)</syntaxhighlight> |
||
==={{header|Sinclair ZX81 BASIC}}=== |
==={{header|Sinclair ZX81 BASIC}}=== |
||
Line 2,193: | Line 2,193: | ||
The disassembly of the Z80 code would be: |
The disassembly of the Z80 code would be: |
||
< |
<syntaxhighlight lang=z80asm> org 4084 |
||
3a 83 40 ld a, (4083) |
3a 83 40 ld a, (4083) |
||
47 ld b, a |
47 ld b, a |
||
Line 2,201: | Line 2,201: | ||
06 00 ld b, 0 |
06 00 ld b, 0 |
||
4f ld c, a ; value in BC reg pair is returned to BASIC |
4f ld c, a ; value in BC reg pair is returned to BASIC |
||
c9 ret</ |
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. |
We then use <code>POKE</code> statements to replace the <code>and</code> instruction with each successive operation we want to perform. |
||
Line 2,208: | Line 2,208: | ||
Finally, observe that the first line reserves 15 bytes for our machine code routine by hiding them in a comment. |
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 |
20 INPUT A |
||
30 INPUT B |
30 INPUT B |
||
Line 2,232: | Line 2,232: | ||
230 POKE 16514,USR 16516 |
230 POKE 16514,USR 16516 |
||
240 NEXT I |
240 NEXT I |
||
250 PRINT A;" << ";B;" = ";PEEK 16514</ |
250 PRINT A;" << ";B;" = ";PEEK 16514</syntaxhighlight> |
||
{{in}} |
{{in}} |
||
<pre>21 |
<pre>21 |
||
Line 2,246: | Line 2,246: | ||
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. |
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 VARIABLES |
||
REM A = first number |
REM A = first number |
||
Line 2,326: | Line 2,326: | ||
IF P = 0 THEN RETURN |
IF P = 0 THEN RETURN |
||
GOTO 500 |
GOTO 500 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
< |
<syntaxhighlight lang=BASIC256># bitwise operators - floating point numbers will be cast to integer |
||
a = 0b00010001 |
a = 0b00010001 |
||
b = 0b11110000 |
b = 0b11110000 |
||
Line 2,336: | Line 2,336: | ||
print a \ 2 # shift right (integer divide by 2) |
print a \ 2 # shift right (integer divide by 2) |
||
print a | b # bitwise or on two integer values |
print a | b # bitwise or on two integer values |
||
print a & b # bitwise or on two integer values</ |
print a & b # bitwise or on two integer values</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
Line 2,344: | Line 2,344: | ||
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. |
The following script (bitops.bat) not only demonstrates the basic bit operations, it also uses bit operations to convert each integral value into a string of 32 binary digits. |
||
< |
<syntaxhighlight lang=dos> |
||
@echo off |
@echo off |
||
setlocal |
setlocal |
||
Line 2,418: | Line 2,418: | ||
) |
) |
||
exit /b |
exit /b |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample output |
Sample output |
||
Line 2,465: | Line 2,465: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang=bbcbasic> number1% = &89ABCDEF |
||
number2% = 8 |
number2% = 8 |
||
Line 2,476: | Line 2,476: | ||
PRINT ~ number1% >> number2% : REM right shift (arithmetic) |
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 left rotate |
||
PRINT ~ (number1% >>> number2%) OR (number1% << (32-number2%)) : REM right rotate</ |
PRINT ~ (number1% >>> number2%) OR (number1% << (32-number2%)) : REM right rotate</syntaxhighlight> |
||
=={{header|beeswax}}== |
=={{header|beeswax}}== |
||
< |
<syntaxhighlight lang=beeswax>#eX~T~T_# |
||
###>N{` AND `~{~` = `&{Nz1~3J |
###>N{` AND `~{~` = `&{Nz1~3J |
||
UXe# |
UXe# |
||
Line 2,503: | Line 2,503: | ||
### |
### |
||
>UX`-`!P{M!` >> `~{~` = `!)!`-`M!{` , interpreted as (negative) signed Int64 number (MSB=1)`NN; |
>UX`-`!P{M!` >> `~{~` = `!)!`-`M!{` , interpreted as (negative) signed Int64 number (MSB=1)`NN; |
||
#>e#</ |
#>e#</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang=Julia> |
||
julia> beeswax("Bitops.bswx",0,0.0,Int(20000)) |
julia> beeswax("Bitops.bswx",0,0.0,Int(20000)) |
||
i9223653511831486512 |
i9223653511831486512 |
||
Line 2,525: | Line 2,525: | ||
logical shift right, and negating the result again: |
logical shift right, and negating the result again: |
||
-9223090561878065104 >> 48 = -32767 , interpreted as (negative) signed Int64 number (MSB=1)</ |
-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. |
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 |
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. |
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: |
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)</ |
A ROR B = A>>>(B%64)+A<<(64-B%64)</syntaxhighlight> |
||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
< |
<syntaxhighlight lang=befunge>> v MCR >v |
||
1 2 3 4 5 6>61g-:| 8 9 |
1 2 3 4 5 6>61g-:| 8 9 |
||
>&&\481p >88*61p371p >:61g\`!:68*+71g81gp| 7 >61g2/61p71g1+71pv |
>&&\481p >88*61p371p >:61g\`!:68*+71g81gp| 7 >61g2/61p71g1+71pv |
||
Line 2,561: | Line 2,561: | ||
^ < G |
^ < G |
||
</syntaxhighlight> |
|||
</lang> |
|||
The labelled points (1 to G) are: |
The labelled points (1 to G) are: |
||
1. Read in A and B, |
1. Read in A and B, |
||
Line 2,592: | Line 2,592: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang=c>void bitwise(int a, int b) |
||
{ |
{ |
||
printf("a and b: %d\n", a & b); |
printf("a and b: %d\n", a & b); |
||
Line 2,605: | Line 2,605: | ||
/* there are no rotation operators in C */ |
/* there are no rotation operators in C */ |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
To rotate an integer, you can combine a left shift and a right shift: |
To rotate an integer, you can combine a left shift and a right shift: |
||
< |
<syntaxhighlight lang=C>/* rotate x to the right by s bits */ |
||
unsigned int rotr(unsigned int x, unsigned int s) |
unsigned int rotr(unsigned int x, unsigned int s) |
||
{ |
{ |
||
return (x >> s) | (x << 32 - s); |
return (x >> s) | (x << 32 - s); |
||
}</ |
}</syntaxhighlight>With a smart enough compiler, the above actually compiles into a single machine bit rotate instruction when possible. E.g. <code>gcc -S</code> on IA32 produced following assembly code:<syntaxhighlight lang=Assembly>rotr: |
||
movl 4(%esp), %eax ; arg1: x |
movl 4(%esp), %eax ; arg1: x |
||
movl 8(%esp), %ecx ; arg2: s |
movl 8(%esp), %ecx ; arg2: s |
||
rorl %cl, %eax ; right rotate x by s |
rorl %cl, %eax ; right rotate x by s |
||
ret</ |
ret</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang=csharp>static void bitwise(int a, int b) |
||
{ |
{ |
||
Console.WriteLine("a and b is {0}", a & b); |
Console.WriteLine("a and b is {0}", a & b); |
||
Line 2,632: | Line 2,632: | ||
// the operator performs a logical shift right |
// the operator performs a logical shift right |
||
// there are no rotation operators in C# |
// there are no rotation operators in C# |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang=cpp>#include <iostream> |
||
void bitwise(int a, int b) |
void bitwise(int a, int b) |
||
Line 2,658: | Line 2,658: | ||
std::cout << "a ror b: " << std::rotr(ua, b) << '\n'; |
std::cout << "a ror b: " << std::rotr(ua, b) << '\n'; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang=lisp>(bit-and x y) |
||
(bit-or x y) |
(bit-or x y) |
||
(bit-xor x y) |
(bit-xor x y) |
||
Line 2,667: | Line 2,667: | ||
(bit-shift-left x n) |
(bit-shift-left x n) |
||
(bit-shift-right x n) |
(bit-shift-right x n) |
||
;;There is no built-in for rotation.</ |
;;There is no built-in for rotation.</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Results are displayed in decimal. |
Results are displayed in decimal. |
||
< |
<syntaxhighlight lang=cobol> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. bitwise-ops. |
PROGRAM-ID. bitwise-ops. |
||
Line 2,705: | Line 2,705: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
{{works with|Visual COBOL}} |
{{works with|Visual COBOL}} |
||
< |
<syntaxhighlight lang=cobol> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. mf-bitwise-ops. |
PROGRAM-ID. mf-bitwise-ops. |
||
Line 2,748: | Line 2,748: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{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 |
CoffeeScript provides sugar for some JavaScript operators, but the bitwise operators are taken directly from JS. See more here: http://coffeescript.org/#operators |
||
< |
<syntaxhighlight lang=coffeescript> |
||
f = (a, b) -> |
f = (a, b) -> |
||
p "and", a & b |
p "and", a & b |
||
Line 2,766: | Line 2,766: | ||
f(10,2) |
f(10,2) |
||
</syntaxhighlight> |
|||
</lang> |
|||
output |
output |
||
<lang> |
<syntaxhighlight lang=text> |
||
> coffee foo.coffee |
> coffee foo.coffee |
||
and 2 |
and 2 |
||
Line 2,777: | Line 2,777: | ||
<< 40 |
<< 40 |
||
>> 2 |
>> 2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang=lisp>(defun bitwise (a b) |
||
(print (logand a b)) ; AND |
(print (logand a b)) ; AND |
||
(print (logior a b)) ; OR ("ior" = inclusive or) |
(print (logior a b)) ; OR ("ior" = inclusive or) |
||
Line 2,788: | Line 2,788: | ||
(print (ash a (- b))) ; arithmetic right shift (negative 2nd arg) |
(print (ash a (- b))) ; arithmetic right shift (negative 2nd arg) |
||
; no logical shift |
; no logical shift |
||
)</ |
)</syntaxhighlight> |
||
Left and right logical shift may be implemented by the following functions: |
Left and right logical shift may be implemented by the following functions: |
||
< |
<syntaxhighlight lang=lisp> |
||
(defun shl (x width bits) |
(defun shl (x width bits) |
||
"Compute bitwise left shift of x by 'bits' bits, represented on 'width' bits" |
"Compute bitwise left shift of x by 'bits' bits, represented on 'width' bits" |
||
Line 2,802: | Line 2,802: | ||
(logand (ash x (- bits)) |
(logand (ash x (- bits)) |
||
(1- (ash 1 width)))) |
(1- (ash 1 width)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Left and right rotation may be implemented by the following functions: |
Left and right rotation may be implemented by the following functions: |
||
< |
<syntaxhighlight lang=lisp> |
||
(defun rotl (x width bits) |
(defun rotl (x width bits) |
||
"Compute bitwise left rotation of x by 'bits' bits, represented on 'width' bits" |
"Compute bitwise left rotation of x by 'bits' bits, represented on 'width' bits" |
||
Line 2,820: | Line 2,820: | ||
(logand (ash x (- width (mod bits width))) |
(logand (ash x (- width (mod bits width))) |
||
(1- (ash 1 width))))) |
(1- (ash 1 width))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang=d>T rot(T)(in T x, in int shift) pure nothrow @nogc { |
||
return (x >>> shift) | (x << (T.sizeof * 8 - shift)); |
return (x >>> shift) | (x << (T.sizeof * 8 - shift)); |
||
} |
} |
||
Line 2,845: | Line 2,845: | ||
testBit(a, b); |
testBit(a, b); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Input: a = 255, b = 2 |
<pre>Input: a = 255, b = 2 |
||
Line 2,859: | Line 2,859: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang=Delphi>program Bitwise; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 2,872: | Line 2,872: | ||
// there are no built-in rotation operators in Delphi |
// there are no built-in rotation operators in Delphi |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
< |
<syntaxhighlight lang=Delphi>PrintLn('2 and 3 = '+IntToStr(2 and 3)); |
||
PrintLn('2 or 3 = '+IntToStr(2 or 3)); |
PrintLn('2 or 3 = '+IntToStr(2 or 3)); |
||
PrintLn('2 xor 3 = '+IntToStr(2 xor 3)); |
PrintLn('2 xor 3 = '+IntToStr(2 xor 3)); |
||
PrintLn('not 2 = '+IntToStr(not 2)); |
PrintLn('not 2 = '+IntToStr(not 2)); |
||
PrintLn('2 shl 3 = '+IntToStr(2 shl 3)); |
PrintLn('2 shl 3 = '+IntToStr(2 shl 3)); |
||
PrintLn('2 shr 3 = '+IntToStr(2 shr 3));</ |
PrintLn('2 shr 3 = '+IntToStr(2 shr 3));</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
E provides arbitrary-size integers, so there is no distinct arithmetic and logical shift right. E does not provide bit rotate operations. |
E provides arbitrary-size integers, so there is no distinct arithmetic and logical shift right. E does not provide bit rotate operations. |
||
< |
<syntaxhighlight lang=e>def bitwise(a :int, b :int) { |
||
println(`Bitwise operations: |
println(`Bitwise operations: |
||
a AND b: ${a & b} |
a AND b: ${a & b} |
||
Line 2,894: | Line 2,894: | ||
a right shift b: ${a >> b} |
a right shift b: ${a >> b} |
||
`) |
`) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
< |
<syntaxhighlight lang=ECL> |
||
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION |
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION |
||
BitAND := A & B; |
BitAND := A & B; |
||
Line 2,927: | Line 2,927: | ||
*/ |
*/ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x : |
ELENA 4.x : |
||
< |
<syntaxhighlight lang=elena>import extensions; |
||
extension testOp |
extension testOp |
||
Line 2,949: | Line 2,949: | ||
{ |
{ |
||
console.loadLineTo(new Integer()).bitwiseTest(console.loadLineTo(new Integer())) |
console.loadLineTo(new Integer()).bitwiseTest(console.loadLineTo(new Integer())) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,961: | Line 2,961: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang=elixir>defmodule Bitwise_operation do |
||
use Bitwise |
use Bitwise |
||
Line 2,982: | Line 2,982: | ||
end |
end |
||
Bitwise_operation.test</ |
Bitwise_operation.test</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,006: | Line 3,006: | ||
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate. |
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate. |
||
< |
<syntaxhighlight lang=erlang> |
||
-module(bitwise_operations). |
-module(bitwise_operations). |
||
Line 3,020: | Line 3,020: | ||
io:format("~p bsl ~p = ~p\n",[A,B,A bsl B]), |
io:format("~p bsl ~p = ~p\n",[A,B,A bsl B]), |
||
io:format("~p bsr ~p = ~p\n",[A,B,A bsr B]). |
io:format("~p bsr ~p = ~p\n",[A,B,A bsr B]). |
||
</syntaxhighlight> |
|||
</lang> |
|||
outputs: |
outputs: |
||
< |
<syntaxhighlight lang=erlang> |
||
255 band 170 = 170 |
255 band 170 = 170 |
||
255 bor 170 = 255 |
255 bor 170 = 255 |
||
Line 3,030: | Line 3,030: | ||
255 bsl 170 = 381627307539845370001346183518875822092557105621893120 |
255 bsl 170 = 381627307539845370001346183518875822092557105621893120 |
||
255 bsr 170 = 0 |
255 bsr 170 = 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang=fsharp>let bitwise a b = |
||
printfn "a and b: %d" (a &&& b) |
printfn "a and b: %d" (a &&& b) |
||
printfn "a or b: %d" (a ||| b) |
printfn "a or b: %d" (a ||| b) |
||
Line 3,041: | Line 3,041: | ||
printfn "a shr b: %d" (a >>> b) // arithmetic shift |
printfn "a shr b: %d" (a >>> b) // arithmetic shift |
||
printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift |
printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift |
||
// No rotation operators.</ |
// No rotation operators.</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang=factor>"a=" "b=" [ write readln string>number ] bi@ |
||
{ |
{ |
||
[ bitand "a AND b: " write . ] |
[ bitand "a AND b: " write . ] |
||
Line 3,052: | Line 3,052: | ||
[ abs shift "a asl b: " write . ] |
[ abs shift "a asl b: " write . ] |
||
[ neg shift "a asr b: " write . ] |
[ neg shift "a asr b: " write . ] |
||
} 2cleave</ |
} 2cleave</syntaxhighlight> |
||
outputs: |
outputs: |
||
< |
<syntaxhighlight lang=factor>a=255 |
||
b=5 |
b=5 |
||
a AND b: 5 |
a AND b: 5 |
||
Line 3,062: | Line 3,062: | ||
NOT a: -256 |
NOT a: -256 |
||
a asl b: 8160 |
a asl b: 8160 |
||
a asr b: 7</ |
a asr b: 7</syntaxhighlight> |
||
Currently rotation and logical shifts are not implemented. |
Currently rotation and logical shifts are not implemented. |
||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
Only AND, OR, and NOT are available. |
Only AND, OR, and NOT are available. |
||
< |
<syntaxhighlight lang=false>10 3 |
||
\$@$@$@$@\ { 3 copies } |
\$@$@$@$@\ { 3 copies } |
||
"a & b = "&." |
"a & b = "&." |
||
a | b = "|." |
a | b = "|." |
||
~a = "%~." |
~a = "%~." |
||
"</ |
"</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang=forth>: arshift 0 ?do 2/ loop ; \ 2/ is an arithmetic shift right by one bit (2* shifts left one bit) |
||
: bitwise ( a b -- ) |
: bitwise ( a b -- ) |
||
cr ." a = " over . ." b = " dup . |
cr ." a = " over . ." b = " dup . |
||
Line 3,085: | Line 3,085: | ||
cr ." a shr b = " 2dup rshift . |
cr ." a shr b = " 2dup rshift . |
||
cr ." a ashr b = " 2dup arshift . |
cr ." a ashr b = " 2dup arshift . |
||
2drop ;</ |
2drop ;</syntaxhighlight> |
||
Rotation is not standard, but may be provided in particular Forth implementations, or as an assembly instruction in CODE words. |
Rotation is not standard, but may be provided in particular Forth implementations, or as an assembly instruction in CODE words. |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In ISO Fortran 90 and later the following BIT INTRINSIC functions are defined: |
In ISO Fortran 90 and later the following BIT INTRINSIC functions are defined: |
||
< |
<syntaxhighlight lang=fortran>integer :: i, j = -1, k = 42 |
||
logical :: a |
logical :: a |
||
Line 3,116: | Line 3,116: | ||
! returns them as the rightmost bits of an otherwise |
! returns them as the rightmost bits of an otherwise |
||
! zero-filled integer. For non-negative K this is |
! zero-filled integer. For non-negative K this is |
||
! arithmetically equivalent to: MOD((K / 2**7), 2**8)</ |
! arithmetically equivalent to: MOD((K / 2**7), 2**8)</syntaxhighlight> |
||
The following INTRINSIC ELEMENTAL SUBROUTINE is also defined: |
The following INTRINSIC ELEMENTAL SUBROUTINE is also defined: |
||
< |
<syntaxhighlight lang=fortran> call mvbits(k, 2, 4, j, 0) ! copy a sequence of 4 bits from k starting at bit 2 into j starting at bit 0</syntaxhighlight> |
||
< |
<syntaxhighlight lang=fortran> |
||
program bits_rosetta |
program bits_rosetta |
||
implicit none |
implicit none |
||
Line 3,146: | Line 3,146: | ||
end program bits_rosetta |
end program bits_rosetta |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output |
Output |
||
<lang> |
<syntaxhighlight lang=text> |
||
Input a= 14 b= 3 |
Input a= 14 b= 3 |
||
AND : 00000000000000000000000000001110 & 00000000000000000000000000000011 = 00000000000000000000000000000010 2 |
AND : 00000000000000000000000000001110 & 00000000000000000000000000000011 = 00000000000000000000000000000010 2 |
||
Line 3,157: | Line 3,157: | ||
NOT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11111111111111111111111111110001 -15 |
NOT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11111111111111111111111111110001 -15 |
||
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823 |
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Free Pascal}}== |
=={{header|Free Pascal}}== |
||
< |
<syntaxhighlight lang=pascal>program Bitwise; |
||
{$mode objfpc} |
{$mode objfpc} |
||
var |
var |
||
Line 3,178: | Line 3,178: | ||
writeln('2 sar 3 = ', sarshortint(x,y)); |
writeln('2 sar 3 = ', sarshortint(x,y)); |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang=freebasic> |
||
' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits) |
' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits) |
||
Line 3,251: | Line 3,251: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,270: | Line 3,270: | ||
=={{header|FutureBasic}}== |
=={{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. |
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 rotl( b as long, n as long ) as long = ( ( 2^n * b) mod 256) or (b > 127) |
||
Line 3,294: | Line 3,294: | ||
fn bitwise( 255, 2 ) |
fn bitwise( 255, 2 ) |
||
HandleEvents</ |
HandleEvents</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,315: | Line 3,315: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang=go>package main |
||
import "fmt" |
import "fmt" |
||
Line 3,352: | Line 3,352: | ||
var a, b int16 = -460, 6 |
var a, b int16 = -460, 6 |
||
bitwise(a, b) |
bitwise(a, b) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>a: 1111111000110100 |
<pre>a: 1111111000110100 |
||
Line 3,368: | Line 3,368: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang=groovy>def bitwise = { a, b -> |
||
println """ |
println """ |
||
a & b = ${a} & ${b} = ${a & b} |
a & b = ${a} & ${b} = ${a & b} |
||
Line 3,378: | Line 3,378: | ||
a >>> b = ${a} >>> ${b} = ${a >>> b} logical (zero-filling) shift |
a >>> b = ${a} >>> ${b} = ${a >>> b} logical (zero-filling) shift |
||
""" |
""" |
||
}</ |
}</syntaxhighlight> |
||
Program: |
Program: |
||
<lang |
<syntaxhighlight lang=groovy>bitwise(-15,3)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,395: | Line 3,395: | ||
Harbour language has a set of core functions, which are fully optimized |
Harbour language has a set of core functions, which are fully optimized |
||
at compile time, to perform bitwise operations. |
at compile time, to perform bitwise operations. |
||
< |
<syntaxhighlight lang=visualfoxpro> |
||
PROCEDURE Main(...) |
PROCEDURE Main(...) |
||
local n1 := 42, n2 := 2 |
local n1 := 42, n2 := 2 |
||
Line 3,439: | Line 3,439: | ||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Bitwise operations with two integers |
Bitwise operations with two integers |
||
Line 3,458: | Line 3,458: | ||
The operations in ''Data.Bits'' work on ''Int'', ''Integer'', and any of the sized integer and word types. |
The operations in ''Data.Bits'' work on ''Int'', ''Integer'', and any of the sized integer and word types. |
||
< |
<syntaxhighlight lang=haskell>import Data.Bits |
||
bitwise :: Int -> Int -> IO () |
bitwise :: Int -> Int -> IO () |
||
Line 3,481: | Line 3,481: | ||
main :: IO () |
main :: IO () |
||
main = bitwise 255 170</ |
main = bitwise 255 170</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>170 |
<pre>170 |
||
Line 3,503: | Line 3,503: | ||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
There is no rotate and no shift support built in to HicEst |
There is no rotate and no shift support built in to HicEst |
||
< |
<syntaxhighlight lang=hicest>i = IAND(k, j) |
||
i = IOR( k, j) |
i = IOR( k, j) |
||
i = IEOR(k, j) |
i = IEOR(k, j) |
||
i = NOT( k )</ |
i = NOT( k )</syntaxhighlight> |
||
=={{header|HPPPL}}== |
=={{header|HPPPL}}== |
||
< |
<syntaxhighlight lang=hpppl>EXPORT BITOPS(a, b) |
||
BEGIN |
BEGIN |
||
PRINT(BITAND(a, b)); |
PRINT(BITAND(a, b)); |
||
Line 3,518: | Line 3,518: | ||
PRINT(BITSR(a, b)); |
PRINT(BITSR(a, b)); |
||
// HPPPL has no builtin rotates or arithmetic right shift. |
// HPPPL has no builtin rotates or arithmetic right shift. |
||
END;</ |
END;</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang=Icon>procedure main() |
||
bitdemo(255,2) |
bitdemo(255,2) |
||
bitdemo(-15,3) |
bitdemo(-15,3) |
||
Line 3,541: | Line 3,541: | ||
procedure demowrite(vs,v) |
procedure demowrite(vs,v) |
||
return write(vs, ": ", v, " = ", int2bit(v),"b") |
return write(vs, ": ", v, " = ", int2bit(v),"b") |
||
end</ |
end</syntaxhighlight> |
||
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' |
Icon/Unicon implements bitwise operations on integers. Because integers can be transparently large integers operations that require fixed sizes don't make sense and aren't defined. These include rotation and logical shifting (shift is arithmetic) . Please note also that 'not' is a reserved word and the negation function is 'icom' |
||
Line 3,569: | Line 3,569: | ||
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. |
Inform 6 has no xor or rotate operators. It also has no shift operators, although the Z-machine, its usual target architecture, does. These can be accessed with inline assembly, which is done here. |
||
< |
<syntaxhighlight lang=Inform 6>[ bitwise a b temp; |
||
print "a and b: ", a & b, "^"; |
print "a and b: ", a & b, "^"; |
||
print "a or b: ", a | b, "^"; |
print "a or b: ", a | b, "^"; |
||
Line 3,584: | Line 3,584: | ||
print "a >> b (logical): ", temp, "^"; |
print "a >> b (logical): ", temp, "^"; |
||
]; |
]; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
Line 3,590: | Line 3,590: | ||
Here are the "[http://www.jsoftware.com/help/dictionary/dbdotn.htm bitwise operators]": |
Here are the "[http://www.jsoftware.com/help/dictionary/dbdotn.htm bitwise operators]": |
||
< |
<syntaxhighlight lang=j>bAND=: 17 b. NB. 16+#.0 0 0 1 |
||
bOR=: 23 b. NB. 16+#.0 1 1 1 |
bOR=: 23 b. NB. 16+#.0 1 1 1 |
||
bXOR=: 22 b. NB. 16+#.0 1 1 0 |
bXOR=: 22 b. NB. 16+#.0 1 1 0 |
||
Line 3,598: | Line 3,598: | ||
bRAshift=: 34 b.~ - |
bRAshift=: 34 b.~ - |
||
bLrot=: 32 b.~ |
bLrot=: 32 b.~ |
||
bRrot=: 32 b.~ -</ |
bRrot=: 32 b.~ -</syntaxhighlight> |
||
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: |
And here is a routine which takes a list of bitwise operators and two numbers and displays a table of results from combining those two numbers with each of the operators: |
||
< |
<syntaxhighlight lang=j>bitwise=: 1 :0 |
||
: |
: |
||
smoutput (((":x),"1' ',.(>u),.' '),"1":y),"1' => ',"1'.X'{~#:x u`:0 y |
smoutput (((":x),"1' ',.(>u),.' '),"1":y),"1' => ',"1'.X'{~#:x u`:0 y |
||
)</ |
)</syntaxhighlight> |
||
And here they are in action: |
And here they are in action: |
||
< |
<syntaxhighlight lang=j> 254 bAND`bOR`bXOR`b1NOT`bLshift`bRshift`bRAshift`bLrot`bRrot bitwise 3 |
||
254 bAND 3 => ............................X. |
254 bAND 3 => ............................X. |
||
254 bOR 3 => ......................XXXXXXXX |
254 bOR 3 => ......................XXXXXXXX |
||
Line 3,618: | Line 3,618: | ||
254 bRAshift 3 => .........................XXXXX |
254 bRAshift 3 => .........................XXXXX |
||
254 bLrot 3 => ...................XXXXXXX.... |
254 bLrot 3 => ...................XXXXXXX.... |
||
254 bRrot 3 => .........................XXXXX</ |
254 bRrot 3 => .........................XXXXX</syntaxhighlight> |
||
Further test |
Further test |
||
<syntaxhighlight lang=j> |
|||
<lang j> |
|||
bXOR/ 3333 5555 7777 9999 |
bXOR/ 3333 5555 7777 9999 |
||
8664 |
8664 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang=java>public static void bitwise(int a, int b){ |
||
System.out.println("a AND b: " + (a & b)); |
System.out.println("a AND b: " + (a & b)); |
||
System.out.println("a OR b: "+ (a | b)); |
System.out.println("a OR b: "+ (a | b)); |
||
Line 3,637: | Line 3,637: | ||
System.out.println("a rol b: " + Integer.rotateLeft(a, b)); //rotate left, Java 1.5+ |
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+ |
System.out.println("a ror b: " + Integer.rotateRight(a, b)); //rotate right, Java 1.5+ |
||
}</ |
}</syntaxhighlight> |
||
All of the operators may be combined with the <tt>=</tt> operator to save space. For example, the following lines each do the same thing: |
All of the operators may be combined with the <tt>=</tt> operator to save space. For example, the following lines each do the same thing: |
||
< |
<syntaxhighlight lang=java>a <<= 3; |
||
a = a << 3; |
a = a << 3; |
||
a *= 8; //2 * 2 * 2 = 8 |
a *= 8; //2 * 2 * 2 = 8 |
||
a = a * 8;</ |
a = a * 8;</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{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. |
There are no integers in Javascript, but there are still bitwise operators. They will convert their number operands into integers before performing they task. In other languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow and rarely used. |
||
< |
<syntaxhighlight lang=javascript>function bitwise(a, b){ |
||
alert("a AND b: " + (a & b)); |
alert("a AND b: " + (a & b)); |
||
alert("a OR b: "+ (a | b)); |
alert("a OR b: "+ (a | b)); |
||
Line 3,655: | Line 3,655: | ||
alert("a >> b: " + (a >> b)); // arithmetic right shift |
alert("a >> b: " + (a >> b)); // arithmetic right shift |
||
alert("a >>> b: " + (a >>> b)); // logical right shift |
alert("a >>> b: " + (a >>> b)); // logical right shift |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang=julia># Version 5.2 |
||
@show 1 & 2 # AND |
@show 1 & 2 # AND |
||
@show 1 | 2 # OR |
@show 1 | 2 # OR |
||
Line 3,670: | Line 3,670: | ||
@show A ror(A,1) ror(A,2) ror(A,5) # ROTATION RIGHT |
@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 |
@show rol(A,1) rol(A,2) rol(A,5) # ROTATION LEFT |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,691: | Line 3,691: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang=scala>/* for symmetry with Kotlin's other binary bitwise operators |
||
we wrap Java's 'rotate' methods as infix functions */ |
we wrap Java's 'rotate' methods as infix functions */ |
||
infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance) |
infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance) |
||
Line 3,711: | Line 3,711: | ||
println("x ROL y = ${x rol y}") |
println("x ROL y = ${x rol y}") |
||
println("x ROR y = ${x ror y}") |
println("x ROR y = ${x ror y}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,731: | Line 3,731: | ||
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate. |
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate. |
||
< |
<syntaxhighlight lang=lisp>(defun bitwise (a b) |
||
(lists:map |
(lists:map |
||
(lambda (x) (io:format "~p~n" `(,x))) |
(lambda (x) (io:format "~p~n" `(,x))) |
||
Line 3,757: | Line 3,757: | ||
(describe "bsl" a b (bsl a b)) |
(describe "bsl" a b (bsl a b)) |
||
(describe "bsr" a b (bsr a b)))) |
(describe "bsr" a b (bsr a b)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example usage: |
Example usage: |
||
< |
<syntaxhighlight lang=lisp> |
||
> (bitwise 255 170) |
> (bitwise 255 170) |
||
170 |
170 |
||
Line 3,778: | Line 3,778: | ||
ok |
ok |
||
> |
> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
Written as functions. |
Written as functions. |
||
<syntaxhighlight lang=lb> |
|||
<lang lb> |
|||
' bitwise operations on byte-sized variables |
' bitwise operations on byte-sized variables |
||
Line 3,829: | Line 3,829: | ||
dec2Bin$ =right$( "00000000" +dec2Bin$, 8) |
dec2Bin$ =right$( "00000000" +dec2Bin$, 8) |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
Lingo has built-in functions for bitwise AND, OR, XOR and NOT: |
Lingo has built-in functions for bitwise AND, OR, XOR and NOT: |
||
< |
<syntaxhighlight lang=lingo>put bitAND(2,7) |
||
put bitOR(2,7) |
put bitOR(2,7) |
||
put bitXOR(2,7) |
put bitXOR(2,7) |
||
put bitNOT(7)</ |
put bitNOT(7)</syntaxhighlight> |
||
Bit shifting and rotating has to be implemented by custom functions. |
Bit shifting and rotating has to be implemented by custom functions. |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang=LiveCode>put "and:" && (255 bitand 2) & comma into bitops |
||
put " or:" && (255 bitor 2) & comma after bitops |
put " or:" && (255 bitor 2) & comma after bitops |
||
put " xor:" && (255 bitxor 2) & comma after bitops |
put " xor:" && (255 bitxor 2) & comma after bitops |
||
Line 3,847: | Line 3,847: | ||
-- Ouput |
-- Ouput |
||
and: 2, or: 255, xor: 253, not: 4294967040</ |
and: 2, or: 255, xor: 253, not: 4294967040</syntaxhighlight> |
||
LiveCode does not provide built-in bit-shift operations. |
LiveCode does not provide built-in bit-shift operations. |
||
=={{header|LLVM}}== |
=={{header|LLVM}}== |
||
< |
<syntaxhighlight lang=llvm>; ModuleID = 'test.o' |
||
;e means little endian |
;e means little endian |
||
;p: { pointer size : pointer abi : preferred alignment for pointers } |
;p: { pointer size : pointer abi : preferred alignment for pointers } |
||
Line 3,910: | Line 3,910: | ||
;Declare external fuctions |
;Declare external fuctions |
||
declare i32 @printf(i8* nocapture, ...) nounwind</ |
declare i32 @printf(i8* nocapture, ...) nounwind</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
{{works with|UCB Logo}} |
{{works with|UCB Logo}} |
||
< |
<syntaxhighlight lang=logo>to bitwise :a :b |
||
(print [a and b:] BitAnd :a :b) |
(print [a and b:] BitAnd :a :b) |
||
(print [a or b:] BitOr :a :b) |
(print [a or b:] BitOr :a :b) |
||
Line 3,924: | Line 3,924: | ||
(print [-a ashift -b:] AShift minus :a minus :b) |
(print [-a ashift -b:] AShift minus :a minus :b) |
||
end |
end |
||
bitwise 255 5</ |
bitwise 255 5</syntaxhighlight> |
||
The output of this program is: |
The output of this program is: |
||
< |
<syntaxhighlight lang=logo>a and b: 5 |
||
a or b: 255 |
a or b: 255 |
||
a xor b: 250 |
a xor b: 250 |
||
Line 3,932: | Line 3,932: | ||
a lshift b: 8160 |
a lshift b: 8160 |
||
a lshift -b: 7 |
a lshift -b: 7 |
||
-a ashift -b: -8</ |
-a ashift -b: -8</syntaxhighlight> |
||
=={{header|LSE64}}== |
=={{header|LSE64}}== |
||
{{incorrect|LSE64|No reason given.}} |
{{incorrect|LSE64|No reason given.}} |
||
< |
<syntaxhighlight lang=lse64>over : 2 pick |
||
2dup : over over |
2dup : over over |
||
Line 3,946: | Line 3,946: | ||
" not A=" ,t ~ ,h nl |
" not A=" ,t ~ ,h nl |
||
\ a \ 7 bitwise # hex literals</ |
\ a \ 7 bitwise # hex literals</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Line 3,952: | Line 3,952: | ||
LuaBitOp implements bitwise functionality for Lua: |
LuaBitOp implements bitwise functionality for Lua: |
||
< |
<syntaxhighlight lang=lua>local bit = require"bit" |
||
local vb = { |
local vb = { |
||
Line 4,017: | Line 4,017: | ||
assert(bit.bxor(1,2) == 3) |
assert(bit.bxor(1,2) == 3) |
||
assert(bit.bor(1,2,4,8,16,32,64,128) == 255) |
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 |
The ''RiscLua'' dialect, for [http://lua.riscos.org.uk/ '''RISC OS'''], has |
||
Line 4,025: | Line 4,025: | ||
==={{header|Lua 5.3+}}=== |
==={{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: |
As of Lua 5.3 most of the required operations are built-in, and those still missing could be derived from them: |
||
< |
<syntaxhighlight lang=lua>a = 0xAA55AA55 |
||
b = 0x4 |
b = 0x4 |
||
print(string.format("%8X and %8X = %16X", a, b, a&b)) |
print(string.format("%8X and %8X = %16X", a, b, a&b)) |
||
Line 4,039: | Line 4,039: | ||
print(string.format("%8X sar %8X = %16X", a, b, sar(a,b))) |
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 rol %8X = %16X", a, b, rol(a,b))) |
||
print(string.format("%8X ror %8X = %16X", a, b, ror(a,b)))</ |
print(string.format("%8X ror %8X = %16X", a, b, ror(a,b)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>AA55AA55 and 4 = 4 |
<pre>AA55AA55 and 4 = 4 |
||
Line 4,052: | Line 4,052: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang=Maple> |
||
with(Bits): |
with(Bits): |
||
bit:=proc(A,B) |
bit:=proc(A,B) |
||
Line 4,071: | Line 4,071: | ||
return a,b,c,d,e,f,g,i; |
return a,b,c,d,e,f,g,i; |
||
end proc; |
end proc; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}}/ {{header|Wolfram Language}}== |
=={{header|Mathematica}}/ {{header|Wolfram Language}}== |
||
Most functions are built-in or can be made really easily: |
Most functions are built-in or can be made really easily: |
||
< |
<syntaxhighlight lang=Mathematica>(*and xor and or*) |
||
BitAnd[integer1, integer2] |
BitAnd[integer1, integer2] |
||
BitXor[integer1, integer2] |
BitXor[integer1, integer2] |
||
Line 4,092: | Line 4,092: | ||
(*right arithmetic shift*) |
(*right arithmetic shift*) |
||
FromDigits[Prepend[Most[#], #[[1]]], 2] &[IntegerDigits[integer1, 2]]</ |
FromDigits[Prepend[Most[#], #[[1]]], 2] &[IntegerDigits[integer1, 2]]</syntaxhighlight> |
||
The function BitShiftLeft, BitShiftRight, RotateRight, RotateLeft all take a second argument, which is the displacement, by default it is set to 1. BitAnd, BitXor and BitOr can handle more than 2 arguments: |
The function BitShiftLeft, BitShiftRight, RotateRight, RotateLeft all take a second argument, which is the displacement, by default it is set to 1. BitAnd, BitXor and BitOr can handle more than 2 arguments: |
||
< |
<syntaxhighlight lang=Mathematica>BitXor[3333, 5555, 7777, 9999]</syntaxhighlight> |
||
gives back: |
gives back: |
||
<lang |
<syntaxhighlight lang=Mathematica>8664</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{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] |
Newer versions of MATLAB have even more bitwise operations than those demonstrated here. A complete list of bitwise operations for the newest version of MATLAB can be found at [http://www.mathworks.com/help/toolbox/fixedpoint/ref/f20333.html#bp7caxc-42 MathWorks] |
||
< |
<syntaxhighlight lang=MATLAB>function bitwiseOps(a,b) |
||
disp(sprintf('%d and %d = %d', [a b bitand(a,b)])); |
disp(sprintf('%d and %d = %d', [a b bitand(a,b)])); |
||
Line 4,109: | Line 4,109: | ||
disp(sprintf('%d >> %d = %d', [a b bitshift(a,-b)])); |
disp(sprintf('%d >> %d = %d', [a b bitshift(a,-b)])); |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang=MATLAB>>> bitwiseOps(255,2) |
||
255 and 2 = 2 |
255 and 2 = 2 |
||
255 or 2 = 255 |
255 or 2 = 255 |
||
255 xor 2 = 253 |
255 xor 2 = 253 |
||
255 << 2 = 1020 |
255 << 2 = 1020 |
||
255 >> 2 = 63</ |
255 >> 2 = 63</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang=maxima>load(functs)$ |
||
a: 3661$ |
a: 3661$ |
||
Line 4,142: | Line 4,142: | ||
logand(a, -a - 1); |
logand(a, -a - 1); |
||
/* 0 */</ |
/* 0 */</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang=maxscript>fn bitwise a b = |
||
( |
( |
||
format "a and b: %\n" (bit.and a b) |
format "a and b: %\n" (bit.and a b) |
||
Line 4,155: | Line 4,155: | ||
) |
) |
||
bitwise 255 170</ |
bitwise 255 170</syntaxhighlight> |
||
MAXScript doesn't have arithmetic shift or rotate operations. |
MAXScript doesn't have arithmetic shift or rotate operations. |
||
Line 4,162: | Line 4,162: | ||
ML/I only supports bitwise AND and OR operations. These are available from version CKD onwards. |
ML/I only supports bitwise AND and OR operations. These are available from version CKD onwards. |
||
< |
<syntaxhighlight lang=ML/I>MCSKIP "WITH" NL |
||
"" Bitwise operations |
"" Bitwise operations |
||
"" assumes macros on input stream 1, terminal on stream 2 |
"" assumes macros on input stream 1, terminal on stream 2 |
||
Line 4,177: | Line 4,177: | ||
MCSET S1=1 |
MCSET S1=1 |
||
*MCSET S10=2 |
*MCSET S10=2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang=modula3>MODULE Bitwise EXPORTS Main; |
||
IMPORT IO, Fmt, Word; |
IMPORT IO, Fmt, Word; |
||
Line 4,202: | Line 4,202: | ||
BEGIN |
BEGIN |
||
Bitwise(255, 5); |
Bitwise(255, 5); |
||
END Bitwise.</ |
END Bitwise.</syntaxhighlight> |
||
Output: |
Output: |
||
Line 4,217: | Line 4,217: | ||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
< |
<syntaxhighlight lang=ActionScript>/** |
||
<doc> |
<doc> |
||
<h2>bitwise operations</h2> |
<h2>bitwise operations</h2> |
||
Line 4,273: | Line 4,273: | ||
if b == null b = 0; |
if b == null b = 0; |
||
bitwise(a,b);</ |
bitwise(a,b);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,301: | Line 4,301: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang=Nemerle>def i = 255; |
||
def j = 2; |
def j = 2; |
||
Line 4,313: | Line 4,313: | ||
WriteLine($"$(i :> uint) rshift $j is $(c >> j)"); // When the left operand of the >> operator is of an unsigned integral type, |
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 |
// 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</ |
// there are no rotation operators in Nemerle, but you could define your own w/ a macro if you really wanted it</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang=nim>proc bitwise(a, b) = |
||
echo "a and b: " , a and b |
echo "a and b: " , a and b |
||
echo "a or b: ", a or b |
echo "a or b: ", a or b |
||
Line 4,322: | Line 4,322: | ||
echo "not a: ", not a |
echo "not a: ", not a |
||
echo "a << b: ", a shl b |
echo "a << b: ", a shl b |
||
echo "a >> b: ", a shr b</ |
echo "a >> b: ", a shr b</syntaxhighlight> |
||
=={{header|NSIS}}== |
=={{header|NSIS}}== |
||
All bitwise operations in NSIS are handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 IntOp] instruction. |
All bitwise operations in NSIS are handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 IntOp] instruction. |
||
< |
<syntaxhighlight lang=nsis>Function Bitwise |
||
Push $0 |
Push $0 |
||
Push $1 |
Push $1 |
||
Line 4,352: | Line 4,352: | ||
Pop $1 |
Pop $1 |
||
Pop $0 |
Pop $0 |
||
FunctionEnd</ |
FunctionEnd</syntaxhighlight> |
||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
{{Works with|oo2c version 2}} |
{{Works with|oo2c version 2}} |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE Bitwise; |
MODULE Bitwise; |
||
IMPORT |
IMPORT |
||
Line 4,383: | Line 4,383: | ||
Do(10,2); |
Do(10,2); |
||
END Bitwise. |
END Bitwise. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,400: | Line 4,400: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang=objeck>use IO; |
||
bundle Default { |
bundle Default { |
||
Line 4,416: | Line 4,416: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang=ocaml>let bitwise a b = |
||
Printf.printf "a and b: %d\n" (a land b); |
Printf.printf "a and b: %d\n" (a land b); |
||
Printf.printf "a or b: %d\n" (a lor b); |
Printf.printf "a or b: %d\n" (a lor b); |
||
Line 4,427: | Line 4,427: | ||
Printf.printf "a asr b: %d\n" (a asr b); (* arithmetic right shift *) |
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 *) |
Printf.printf "a lsr b: %d\n" (a lsr b); (* logical right shift *) |
||
;;</ |
;;</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
Line 4,433: | Line 4,433: | ||
There's no arithmetic shift nor rotation (and the not can be done through a xor) |
There's no arithmetic shift nor rotation (and the not can be done through a xor) |
||
< |
<syntaxhighlight lang=octave>function bitops(a, b) |
||
s = sprintf("%s %%s %s = %%s\n", dec2bin(a), dec2bin(b)); |
s = sprintf("%s %%s %s = %%s\n", dec2bin(a), dec2bin(b)); |
||
printf(s, "or", dec2bin(bitor(a, b))); |
printf(s, "or", dec2bin(bitor(a, b))); |
||
Line 4,443: | Line 4,443: | ||
endfunction |
endfunction |
||
bitops(0x1e, 0x3);</ |
bitops(0x1e, 0x3);</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 4,449: | Line 4,449: | ||
There is no built-in for not and rotation |
There is no built-in for not and rotation |
||
< |
<syntaxhighlight lang=Oforth>: bitwise(a, b) |
||
a b bitAnd println |
a b bitAnd println |
||
a b bitOr println |
a b bitOr println |
||
a b bitXor println |
a b bitXor println |
||
a bitLeft(b) println |
a bitLeft(b) println |
||
a bitRight(b) println ;</ |
a bitRight(b) println ;</syntaxhighlight> |
||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
< |
<syntaxhighlight lang=ooRexx>/* ooRexx ************************************************************* |
||
/ Bit Operations work as in Rexx (of course) |
/ Bit Operations work as in Rexx (of course) |
||
* Bit operations are performed up to the length of the shorter string. |
* Bit operations are performed up to the length of the shorter string. |
||
Line 4,476: | Line 4,476: | ||
Say 'a~bitor(b,p):'c2b(a~bitor(b,p)) c2x(a~bitor(b,p)) |
Say 'a~bitor(b,p):'c2b(a~bitor(b,p)) c2x(a~bitor(b,p)) |
||
Exit |
Exit |
||
c2b: return x2b(c2x(arg(1)))</ |
c2b: return x2b(c2x(arg(1)))</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 4,494: | Line 4,494: | ||
=={{header|PARI/GP}}== |
=={{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>. |
Pari does not support bitwise rotations, which have no obvious meaning with arbitrary-precision integers. See also <code>bitnegimply</code> for another bitwise operator. For shifts, see also <code>shiftmul</code>. |
||
< |
<syntaxhighlight lang=parigp>bo(a,b)={ |
||
print("And: "bitand(a,b)); |
print("And: "bitand(a,b)); |
||
print("Or: "bitor(a,b)); |
print("Or: "bitor(a,b)); |
||
Line 4,501: | Line 4,501: | ||
print("Left shift: ",a<<b); |
print("Left shift: ",a<<b); |
||
print("Right shift: ",a>>b); |
print("Right shift: ",a>>b); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{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: |
While Standard Pascal does not have bitwise operations, most Pascal implementations (including Turbo Pascal and Delphi) extend the standard logical operators to also provide bitwise operations: |
||
< |
<syntaxhighlight lang=pascal>var |
||
a, b: integer; |
a, b: integer; |
||
begin |
begin |
||
Line 4,513: | Line 4,513: | ||
writeln('a or b = ', a or b); { 14 = 1110 } |
writeln('a or b = ', a or b); { 14 = 1110 } |
||
writeln('a xor b = ', a xor b) { 6 = 0110 } |
writeln('a xor b = ', a xor b) { 6 = 0110 } |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang=perl>use integer; |
||
sub bitwise($$) { |
sub bitwise($$) { |
||
Line 4,530: | Line 4,530: | ||
print 'a << b: ', $a << $b, "\n"; # left shift |
print 'a << b: ', $a << $b, "\n"; # left shift |
||
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift |
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{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)_bits, which each have sequence and unsigned variants. Note careful use of latter (unsigned) routines here, since Phix naturally preserves signs (and common sense) when it can, rather than rudely treat, for instance, +4,294,967,295 as -1, unless explicitly told to do so as it is below. Likewise the builtin shift operators deliver signed and unbounded results, so we'll wrap them here. There are no builtin rotate routines, but easy enough to devise. The distributed copy (1.0.2+) also contains an (older) inline assembly version, which is obviously not JavaScript compatible, but may be significantly faster, for desktop-only applications. |
||
<!--< |
<!--<syntaxhighlight lang=Phix>(phixonline)--> |
||
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Bitwise_operations.exw</span> |
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Bitwise_operations.exw</span> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
Line 4,573: | Line 4,573: | ||
<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> |
<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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,588: | Line 4,588: | ||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang=Phixmonti>6 var a 3 var b |
||
def tab |
def tab |
||
Line 4,604: | Line 4,604: | ||
"OR = " print tab a b bitor printBits |
"OR = " print tab a b bitor printBits |
||
"XOR = " print tab a b bitxor printBits |
"XOR = " print tab a b bitxor printBits |
||
"NOT = " print tab a bitnot printBits</ |
"NOT = " print tab a bitnot printBits</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang=php>function bitwise($a, $b) |
||
{ |
{ |
||
function zerofill($a,$b) { |
function zerofill($a,$b) { |
||
Line 4,621: | Line 4,621: | ||
echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift |
echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift |
||
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift |
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
Line 4,629: | Line 4,629: | ||
Bitwise AND: |
Bitwise AND: |
||
< |
<syntaxhighlight lang=PicoLisp>: (& 6 3) |
||
-> 2 |
-> 2 |
||
: (& 7 3 1) |
: (& 7 3 1) |
||
-> 1</ |
-> 1</syntaxhighlight> |
||
Bitwise AND-Test (tests if all bits in the first argument are set in the |
Bitwise AND-Test (tests if all bits in the first argument are set in the |
||
following arguments): |
following arguments): |
||
< |
<syntaxhighlight lang=PicoLisp>: (bit? 1 2) |
||
-> NIL |
-> NIL |
||
Line 4,643: | Line 4,643: | ||
: (bit? 6 15 255) |
: (bit? 6 15 255) |
||
-> 6</ |
-> 6</syntaxhighlight> |
||
Bitwise OR: |
Bitwise OR: |
||
< |
<syntaxhighlight lang=PicoLisp>: (| 1 2) |
||
-> 3 |
-> 3 |
||
: (| 1 2 4 8) |
: (| 1 2 4 8) |
||
-> 15</ |
-> 15</syntaxhighlight> |
||
Bitwise XOR: |
Bitwise XOR: |
||
< |
<syntaxhighlight lang=PicoLisp>: (x| 2 7) |
||
-> 5 |
-> 5 |
||
: (x| 2 7 1) |
: (x| 2 7 1) |
||
-> 4</ |
-> 4</syntaxhighlight> |
||
Shift (right with a positive count, left with a negative count): |
Shift (right with a positive count, left with a negative count): |
||
< |
<syntaxhighlight lang=PicoLisp>: (>> 1 8) |
||
-> 4 |
-> 4 |
||
Line 4,667: | Line 4,667: | ||
: (>> -1 -16) |
: (>> -1 -16) |
||
-> -32</ |
-> -32</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
Rotate operations are not available |
Rotate operations are not available |
||
< |
<syntaxhighlight lang=Pike> |
||
void bitwise(int a, int b) |
void bitwise(int a, int b) |
||
{ |
{ |
||
Line 4,690: | Line 4,690: | ||
bitwise(255, 30); |
bitwise(255, 30); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 4,703: | Line 4,703: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang=pli>/* PL/I can perform bit operations on binary integers. */ |
||
k = iand(i,j); |
k = iand(i,j); |
||
k = ior(i,j); |
k = ior(i,j); |
||
Line 4,728: | Line 4,728: | ||
u = substr(s, length(s), 1) || substr(s, 1, length(s)-1); /* implements rotate right. */ |
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. */ |
u = substr(s, 2) || substr(s, 1, 1); /* implements rotate left. */ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang=pop11>define bitwise(a, b); |
||
printf(a && b, 'a and b = %p\n'); |
printf(a && b, 'a and b = %p\n'); |
||
printf(a || b, 'a or b = %p\n'); |
printf(a || b, 'a or b = %p\n'); |
||
Line 4,739: | Line 4,739: | ||
printf(a << b, 'left shift of a by b = %p\n'); |
printf(a << b, 'left shift of a by b = %p\n'); |
||
printf(a >> b, 'arithmetic right shift of a by b = %p\n'); |
printf(a >> b, 'arithmetic right shift of a by b = %p\n'); |
||
enddefine;</ |
enddefine;</syntaxhighlight> |
||
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. |
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. |
||
Line 4,748: | Line 4,748: | ||
Logical right shift and rotations are not supported in PowerShell. |
Logical right shift and rotations are not supported in PowerShell. |
||
{{works with|PowerShell|2.0}} |
{{works with|PowerShell|2.0}} |
||
< |
<syntaxhighlight lang=PowerShell>$X -band $Y |
||
$X -bor $Y |
$X -bor $Y |
||
$X -bxor $Y |
$X -bxor $Y |
||
-bnot $X</ |
-bnot $X</syntaxhighlight> |
||
{{works with|PowerShell|3.0}} |
{{works with|PowerShell|3.0}} |
||
< |
<syntaxhighlight lang=PowerShell>$X -shl $Y |
||
# Arithmetic right shift |
# Arithmetic right shift |
||
$X -shr $Y |
$X -shr $Y |
||
# Requires quite a stretch of the imagination to call this "native" support of right rotate, but it works |
# 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))</ |
[System.Security.Cryptography.SHA256Managed].GetMethod('RotateRight', 'NonPublic, Static', $null, @([UInt32], [Int32]), $null).Invoke($null, @([uint32]$X, $Y))</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang=PureBasic>Procedure Bitwise(a, b) |
||
Debug a & b ; And |
Debug a & b ; And |
||
Debug a | b ;Or |
Debug a | b ;Or |
||
Line 4,790: | Line 4,790: | ||
!mov dword [p.v_Temp], edx |
!mov dword [p.v_Temp], edx |
||
Debug Temp |
Debug Temp |
||
EndProcedure</ |
EndProcedure</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
Line 4,800: | Line 4,800: | ||
binary output formatting in calculations and result displays. |
binary output formatting in calculations and result displays. |
||
< |
<syntaxhighlight lang=python>def bitwise_built_ins(width, a, b): |
||
mask = (1 << width) - 1 |
mask = (1 << width) - 1 |
||
print(f"""\ |
print(f"""\ |
||
Line 4,908: | Line 4,908: | ||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
bitwise_built_ins(8, 27, 125) |
bitwise_built_ins(8, 27, 125) |
||
helper_funcs(8, 27)</ |
helper_funcs(8, 27)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,966: | Line 4,966: | ||
===Python 2=== |
===Python 2=== |
||
< |
<syntaxhighlight lang=python>def bitwise(a, b): |
||
print 'a and b:', a & b |
print 'a and b:', a & b |
||
print 'a or b:', a | b |
print 'a or b:', a | b |
||
Line 4,972: | Line 4,972: | ||
print 'not a:', ~a |
print 'not a:', ~a |
||
print 'a << b:', a << b # left shift |
print 'a << b:', a << b # left shift |
||
print 'a >> b:', a >> b # arithmetic right shift</ |
print 'a >> b:', a >> b # arithmetic right shift</syntaxhighlight> |
||
Python does not have built in rotate or logical right shift operations. |
Python does not have built in rotate or logical right shift operations. |
||
Line 4,978: | Line 4,978: | ||
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: |
Note: Newer Python versions (circa 2.4?) will automatically promote integers into "long integers" (arbitrary length, bounded by available memory). This can be noticed especially when using left shift operations. When using bitwise operations one usually wants to keep these bounded to specific sizes such as 8, 16, 32 or 64 bit widths. To do these we use the AND operator with specific values (bitmasks). For example: |
||
< |
<syntaxhighlight lang=python># 8-bit bounded shift: |
||
x = x << n & 0xff |
x = x << n & 0xff |
||
# ditto for 16 bit: |
# ditto for 16 bit: |
||
Line 4,985: | Line 4,985: | ||
x = x << n & 0xffffffff |
x = x << n & 0xffffffff |
||
# ... and 64-bit: |
# ... and 64-bit: |
||
x = x << n & 0xffffffffffffffff</ |
x = x << n & 0xffffffffffffffff</syntaxhighlight> |
||
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. |
We can easily implement our own rotation functions. For left rotations this is down by ORing the left shifted and masked lower bits against the right shifted upper bits. For right rotations we perform the converse operations, ORing a set of right shifted lower bits against the appropriate number of left shifted upper bits. |
||
< |
<syntaxhighlight lang=python>def bitstr(n, width=None): |
||
"""return the binary representation of n as a string and |
"""return the binary representation of n as a string and |
||
optionally zero-fill (pad) it to a given length |
optionally zero-fill (pad) it to a given length |
||
Line 5,029: | Line 5,029: | ||
return n |
return n |
||
n &= mask(width) |
n &= mask(width) |
||
return (n >> rotations) | ((n << (width - rotations)) & mask(width))</ |
return (n >> rotations) | ((n << (width - rotations)) & mask(width))</syntaxhighlight> |
||
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. |
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. |
||
Line 5,035: | Line 5,035: | ||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
< |
<syntaxhighlight lang=QB64> |
||
' no rotations and shift aritmetic are available in QB64 |
' no rotations and shift aritmetic are available in QB64 |
||
' Bitwise operator in Qbasic and QB64 |
' Bitwise operator in Qbasic and QB64 |
||
Line 5,067: | Line 5,067: | ||
Next |
Next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 5,073: | Line 5,073: | ||
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>. |
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 |
64 times |
||
[ 2 /mod |
[ 2 /mod |
||
Line 5,093: | Line 5,093: | ||
say "bitwise RROTATE: " rrot64 echobin ] is task ( n n --> ) |
say "bitwise RROTATE: " rrot64 echobin ] is task ( n n --> ) |
||
hex FFFFF hex F task</ |
hex FFFFF hex F task</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,112: | Line 5,112: | ||
=== Native functions in R 3.x === |
=== Native functions in R 3.x === |
||
< |
<syntaxhighlight lang=rsplus># Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd |
||
a <- 35 |
a <- 35 |
||
Line 5,121: | Line 5,121: | ||
bitwNot(a) |
bitwNot(a) |
||
bitwShiftL(a, 2) |
bitwShiftL(a, 2) |
||
bitwShiftR(a, 2)</ |
bitwShiftR(a, 2)</syntaxhighlight> |
||
See also https://cran.r-project.org/doc/manuals/r-release/NEWS.3.html. |
See also https://cran.r-project.org/doc/manuals/r-release/NEWS.3.html. |
||
===Using ''as.hexmode'' or ''as.octmode''=== |
===Using ''as.hexmode'' or ''as.octmode''=== |
||
< |
<syntaxhighlight lang=rsplus>a <- as.hexmode(35) |
||
b <- as.hexmode(42) |
b <- as.hexmode(42) |
||
as.integer(a & b) # 34 |
as.integer(a & b) # 34 |
||
as.integer(a | b) # 43 |
as.integer(a | b) # 43 |
||
as.integer(xor(a, b)) # 9</ |
as.integer(xor(a, b)) # 9</syntaxhighlight> |
||
===Using ''intToBits''=== |
===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. |
The logical operators in R, namely &, | and !, are designed to work on logical vectors rather than bits. It is possible to convert from integer to logical vector and back to make these work as required, e.g. |
||
< |
<syntaxhighlight lang=rsplus>intToLogicalBits <- function(intx) as.logical(intToBits(intx)) |
||
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb])) |
logicalBitsToInt <- function(lb) as.integer(sum((2^(0:31))[lb])) |
||
"%AND%" <- function(x, y) |
"%AND%" <- function(x, y) |
||
Line 5,146: | Line 5,146: | ||
35 %AND% 42 # 34 |
35 %AND% 42 # 34 |
||
35 %OR% 42 # 42</ |
35 %OR% 42 # 42</syntaxhighlight> |
||
===Using ''bitops'' package=== |
===Using ''bitops'' package=== |
||
< |
<syntaxhighlight lang=rsplus>library(bitops) |
||
bitAnd(35, 42) # 34 |
bitAnd(35, 42) # 34 |
||
bitOr(35, 42) # 43 |
bitOr(35, 42) # 43 |
||
Line 5,156: | Line 5,156: | ||
bitShiftL(35, 1) # 70 |
bitShiftL(35, 1) # 70 |
||
bitShiftR(35, 1) # 17 |
bitShiftR(35, 1) # 17 |
||
# Note that no bit rotation is provided in this package</ |
# Note that no bit rotation is provided in this package</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang=racket> |
||
#lang racket |
#lang racket |
||
(define a 255) |
(define a 255) |
||
Line 5,169: | Line 5,169: | ||
(arithmetic-shift a b) ; left shift |
(arithmetic-shift a b) ; left shift |
||
(arithmetic-shift a (- b))) ; right shift |
(arithmetic-shift a (- b))) ; right shift |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 5,178: | Line 5,178: | ||
(formerly Perl 6) |
(formerly Perl 6) |
||
{{works with|Rakudo|2017.05}} |
{{works with|Rakudo|2017.05}} |
||
<lang |
<syntaxhighlight lang=raku line>constant MAXINT = uint.Range.max; |
||
constant BITS = MAXINT.base(2).chars; |
constant BITS = MAXINT.base(2).chars; |
||
Line 5,205: | Line 5,205: | ||
sub say_bit ($message, $value) { |
sub say_bit ($message, $value) { |
||
printf("%30s: %{'0' ~ BITS}b\n", $message, $value +& MAXINT); |
printf("%30s: %{'0' ~ BITS}b\n", $message, $value +& MAXINT); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 7: 0000000000000000000000000000000000000000000000000000000000000111 |
<pre> 7: 0000000000000000000000000000000000000000000000000000000000000111 |
||
Line 5,232: | Line 5,232: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang=red>Red [Source: https://github.com/vazub/rosetta-red] |
||
a: 10 |
a: 10 |
||
Line 5,249: | Line 5,249: | ||
; there are no circular shift operators in Red |
; there are no circular shift operators in Red |
||
] |
] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,266: | Line 5,266: | ||
There is no predefined arithmetic shifts in Retro. |
There is no predefined arithmetic shifts in Retro. |
||
< |
<syntaxhighlight lang=Retro> |
||
: bitwise ( ab- ) |
: bitwise ( ab- ) |
||
cr |
cr |
||
Line 5,277: | Line 5,277: | ||
2over << "a << b = %d\n" puts |
2over << "a << b = %d\n" puts |
||
2over >> "a >> b = %d\n" puts |
2over >> "a >> b = %d\n" puts |
||
2drop ;</ |
2drop ;</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 5,290: | Line 5,290: | ||
╚═══════════════════════════════════════════════════════════════════════════════════════╝ |
╚═══════════════════════════════════════════════════════════════════════════════════════╝ |
||
</pre> |
</pre> |
||
< |
<syntaxhighlight lang=rexx>/*REXX program performs bit─wise operations on integers: & | && ¬ «L »R */ |
||
numeric digits 1000 /*be able to handle ginormous integers.*/ |
numeric digits 1000 /*be able to handle ginormous integers.*/ |
||
say center('decimal', 9) center("value", 9) center('bits', 50) |
say center('decimal', 9) center("value", 9) center('bits', 50) |
||
Line 5,312: | Line 5,312: | ||
bOr: return c2d( bitor( d2c( arg(1) ), d2c( arg(2) ) ) ) |
bOr: return c2d( bitor( d2c( arg(1) ), d2c( arg(2) ) ) ) |
||
bXor: return c2d( bitxor( d2c( arg(1) ), d2c( arg(2) ) ) ) |
bXor: return c2d( bitxor( d2c( arg(1) ), d2c( arg(2) ) ) ) |
||
bShiftR: $=substr(reverse(d2b(arg(1))),arg(2)+1); if $='' then $=0; return b2d(reverse($))</ |
bShiftR: $=substr(reverse(d2b(arg(1))),arg(2)+1); if $='' then $=0; return b2d(reverse($))</syntaxhighlight> |
||
{{out|output}} |
{{out|output}} |
||
<pre> |
<pre> |
||
Line 5,328: | Line 5,328: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang=ring> |
||
x = 8 |
x = 8 |
||
y = 2 |
y = 2 |
||
Line 5,338: | Line 5,338: | ||
see "x << y - Binary Left Shift : " + (x << y) + nl |
see "x << y - Binary Left Shift : " + (x << y) + nl |
||
see "x >> y - Binary Right Shift : " + (x >> y) + nl |
see "x >> y - Binary Right Shift : " + (x >> y) + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
Line 5,345: | Line 5,345: | ||
are integers then the result of the operation is an integer as well. |
are integers then the result of the operation is an integer as well. |
||
< |
<syntaxhighlight lang=RLaB>>> x = int(3); |
||
>> y = int(1); |
>> y = int(1); |
||
>> z = x && y; printf("0x%08x\n",z); // logical 'and' |
>> z = x && y; printf("0x%08x\n",z); // logical 'and' |
||
Line 5,357: | Line 5,357: | ||
0x00000006 |
0x00000006 |
||
>> z = x / i2; printf("0x%08x\n",z); // right-shift is division by 2 where both arguments are integers |
>> z = x / i2; printf("0x%08x\n",z); // right-shift is division by 2 where both arguments are integers |
||
0x00000001</ |
0x00000001</syntaxhighlight> |
||
=={{header|Robotic}}== |
=={{header|Robotic}}== |
||
< |
<syntaxhighlight lang=robotic> |
||
input string "First value" |
input string "First value" |
||
set "local1" to "input" |
set "local1" to "input" |
||
Line 5,376: | Line 5,376: | ||
end |
end |
||
. "Bitwise rotation is not natively supported" |
. "Bitwise rotation is not natively supported" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang=ruby>def bitwise(a, b) |
||
form = "%1$7s:%2$6d %2$016b" |
form = "%1$7s:%2$6d %2$016b" |
||
puts form % ["a", a] |
puts form % ["a", a] |
||
Line 5,391: | Line 5,391: | ||
end |
end |
||
bitwise(14,3)</ |
bitwise(14,3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,406: | Line 5,406: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang=rust>fn main() { |
||
let a: u8 = 105; |
let a: u8 = 105; |
||
let b: u8 = 91; |
let b: u8 = 91; |
||
Line 5,417: | Line 5,417: | ||
println!("a << 3 = {:0>8b}", a << 3); |
println!("a << 3 = {:0>8b}", a << 3); |
||
println!("a >> 3 = {:0>8b}", a >> 3); |
println!("a >> 3 = {:0>8b}", a >> 3); |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 5,433: | Line 5,433: | ||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
< |
<syntaxhighlight lang=sas>/* rotations are not available, but are easy to implement with the other bitwise operators */ |
||
data _null_; |
data _null_; |
||
a=105; |
a=105; |
||
Line 5,444: | Line 5,444: | ||
h=brshift(a,1); |
h=brshift(a,1); |
||
put _all_; |
put _all_; |
||
run;</ |
run;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang=scala>def bitwise(a: Int, b: Int) { |
||
println("a and b: " + (a & b)) |
println("a and b: " + (a & b)) |
||
println("a or b: " + (a | b)) |
println("a or b: " + (a | b)) |
||
Line 5,458: | Line 5,458: | ||
println("a rot b: " + Integer.rotateLeft(a, b)) // Rotate Left |
println("a rot b: " + Integer.rotateLeft(a, b)) // Rotate Left |
||
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right |
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
{{Works with|Scheme|R<math>^6</math>RS}} |
{{Works with|Scheme|R<math>^6</math>RS}} |
||
< |
<syntaxhighlight lang=scheme>(import (rnrs arithmetic bitwise (6))) |
||
(define (bitwise a b) |
(define (bitwise a b) |
||
Line 5,476: | Line 5,476: | ||
(newline)) |
(newline)) |
||
(bitwise 255 5)</ |
(bitwise 255 5)</syntaxhighlight> |
||
Output: |
Output: |
||
<lang>5 |
<syntaxhighlight lang=text>5 |
||
255 |
255 |
||
250 |
250 |
||
-256 |
-256 |
||
7</ |
7</syntaxhighlight> |
||
''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).'' |
''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).'' |
||
Line 5,494: | Line 5,494: | ||
Right shifting of bin32 values is done with logical shifts. |
Right shifting of bin32 values is done with logical shifts. |
||
< |
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i"; |
||
include "bin32.s7i"; |
include "bin32.s7i"; |
||
Line 5,523: | Line 5,523: | ||
bitwise(65076, 6); |
bitwise(65076, 6); |
||
bitwise(bin32(65076), bin32(6)); |
bitwise(bin32(65076), bin32(6)); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,544: | Line 5,544: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang=ruby>func bitwise(a, b) { |
||
say ('a and b : ', a & b) |
say ('a and b : ', a & b) |
||
say ('a or b : ', a | b) |
say ('a or b : ', a | b) |
||
Line 5,553: | Line 5,553: | ||
} |
} |
||
bitwise(14,3)</ |
bitwise(14,3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,565: | Line 5,565: | ||
=={{header|Simula}}== |
=={{header|Simula}}== |
||
< |
<syntaxhighlight lang=simula>BEGIN |
||
COMMENT TO MY KNOWLEDGE SIMULA DOES NOT SUPPORT BITWISE OPERATIONS SO WE MUST WRITE PROCEDURES FOR THE JOB ; |
COMMENT TO MY KNOWLEDGE SIMULA DOES NOT SUPPORT BITWISE OPERATIONS SO WE MUST WRITE PROCEDURES FOR THE JOB ; |
||
INTEGER WORDSIZE; |
INTEGER WORDSIZE; |
||
Line 5,667: | Line 5,667: | ||
END; |
END; |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>A AND B : 2 |
<pre>A AND B : 2 |
||
Line 5,680: | Line 5,680: | ||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang=slate>[ |:a :b | |
||
inform: (a bitAnd: b) printString. |
inform: (a bitAnd: b) printString. |
||
Line 5,689: | Line 5,689: | ||
inform: (a >> b) printString. |
inform: (a >> b) printString. |
||
] applyTo: {8. 12}.</ |
] applyTo: {8. 12}.</syntaxhighlight> |
||
'''Bold text''' |
'''Bold text''' |
||
Line 5,697: | Line 5,697: | ||
{{works with|VisualWorks Smalltalk}} |
{{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. |
Since [[GNU Smalltalk]] by default runs without a graphical user interface, I wrote the program in that dialect. The actual methods for bitwise operations (''bitAnd:'', etc.) are the same in all implementations. |
||
< |
<syntaxhighlight lang=smalltalk>| testBitFunc | |
||
testBitFunc := [ :a :b | |
testBitFunc := [ :a :b | |
||
('%1 and %2 is %3' % { a. b. (a bitAnd: b) }) displayNl. |
('%1 and %2 is %3' % { a. b. (a bitAnd: b) }) displayNl. |
||
Line 5,706: | Line 5,706: | ||
('%1 right shift %2 is %3' % { a. b. (a bitShift: (b negated)) }) displayNl. |
('%1 right shift %2 is %3' % { a. b. (a bitShift: (b negated)) }) displayNl. |
||
]. |
]. |
||
testBitFunc value: 16r7F value: 4 .</ |
testBitFunc value: 16r7F value: 4 .</syntaxhighlight> |
||
in addition to the above, |
in addition to the above, |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
< |
<syntaxhighlight lang=smalltalk>(a bitClear: b) "mask out bits" |
||
(a bitAt: index) "retrieve a bit (bit-index, one-based)" |
(a bitAt: index) "retrieve a bit (bit-index, one-based)" |
||
(a setBit: index) "set a bit (bit-index)" |
(a setBit: index) "set a bit (bit-index)" |
||
Line 5,717: | Line 5,717: | ||
lowBit "find the index of the lowest one-bit; zero if none" |
lowBit "find the index of the lowest one-bit; zero if none" |
||
highBit "find the index of the highest one-bit; zero if none" |
highBit "find the index of the highest one-bit; zero if none" |
||
bitCount "count the one-bits"</ |
bitCount "count the one-bits"</syntaxhighlight> |
||
Notice that all of those work on arbitrarily large integers (i.e. 1000 factorial lowBit -> 995). |
Notice that all of those work on arbitrarily large integers (i.e. 1000 factorial lowBit -> 995). |
||
Line 5,723: | Line 5,723: | ||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
For integers, IntInfs provide bitwise operations: |
For integers, IntInfs provide bitwise operations: |
||
< |
<syntaxhighlight lang=sml>fun bitwise_ints (a, b) = ( |
||
print ("a and b: " ^ IntInf.toString (IntInf.andb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n"); |
print ("a 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"); |
print ("a or b: " ^ IntInf.toString (IntInf.orb (IntInf.fromInt a, IntInf.fromInt b)) ^ "\n"); |
||
Line 5,730: | Line 5,730: | ||
print ("a lsl b: " ^ IntInf.toString (IntInf.<< (IntInf.fromInt a, Word.fromInt b )) ^ "\n"); (* left shift *) |
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 *) |
print ("a asr b: " ^ IntInf.toString (IntInf.~>> (IntInf.fromInt a, Word.fromInt b )) ^ "\n") (* arithmetic right shift *) |
||
)</ |
)</syntaxhighlight> |
||
More shifts are available for words (unsigned ints): |
More shifts are available for words (unsigned ints): |
||
< |
<syntaxhighlight lang=sml>fun bitwise_words (a, b) = ( |
||
print ("a and b: " ^ Word.fmt StringCvt.DEC (Word.andb (a, b)) ^ "\n"); |
print ("a and b: " ^ Word.fmt StringCvt.DEC (Word.andb (a, b)) ^ "\n"); |
||
print ("a or b: " ^ Word.fmt StringCvt.DEC (Word.orb (a, b)) ^ "\n"); |
print ("a or b: " ^ Word.fmt StringCvt.DEC (Word.orb (a, b)) ^ "\n"); |
||
Line 5,740: | Line 5,740: | ||
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"); (* arithmetic right shift *) |
||
print ("a asr b: " ^ Word.fmt StringCvt.DEC (Word.>> (a, b) ) ^ "\n") (* logical right shift *) |
print ("a asr b: " ^ Word.fmt StringCvt.DEC (Word.>> (a, b) ) ^ "\n") (* logical right shift *) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
Line 5,746: | Line 5,746: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang=swift>func bitwise(a: Int, b: Int) { |
||
// All bitwise operations (including shifts) |
// All bitwise operations (including shifts) |
||
// require both operands to be the same type |
// require both operands to be the same type |
||
Line 5,760: | Line 5,760: | ||
} |
} |
||
bitwise(-15,3)</ |
bitwise(-15,3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,774: | Line 5,774: | ||
=={{header|SystemVerilog}}== |
=={{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: |
Verilog, being a hardware description language, had pretty comprehensive support for bit twiddling; though rotation is still a slightly manual operation. Just to be different, I decided to use a couple of 53-bit integers: |
||
< |
<syntaxhighlight lang=SystemVerilog>program main; |
||
initial begin |
initial begin |
||
Line 5,793: | Line 5,793: | ||
end |
end |
||
endprogram</ |
endprogram</syntaxhighlight> |
||
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: |
If we want to do a variable bit rotation, then we need to think in hardware terms, and build a mux structure (this could be a function, but using a module allows it to be parameterized: |
||
< |
<syntaxhighlight lang=SystemVerilog>module rotate(in, out, shift); |
||
parameter BITS = 32; |
parameter BITS = 32; |
||
Line 5,808: | Line 5,808: | ||
always_comb foreach (out[i]) out[i] = in[ (i+shift) % BITS ]; |
always_comb foreach (out[i]) out[i] = in[ (i+shift) % BITS ]; |
||
endmodule</ |
endmodule</syntaxhighlight> |
||
of course, one could always write the foreach loop inline. |
of course, one could always write the foreach loop inline. |
||
Line 5,814: | Line 5,814: | ||
=={{header|Tailspin}}== |
=={{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. |
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 a: [x f075 x]; |
||
def b: [x 81 x]; |
def b: [x 81 x]; |
||
Line 5,827: | Line 5,827: | ||
$a::shift&{left: 3, fill: $a} -> '$a; rotated left 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 |
$a::shift&{left: -3, fill: $a} -> '$a; rotated right 3 bits is $;$#10;' -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,842: | Line 5,842: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang=tcl>proc bitwise {a b} { |
||
puts [format "a and b: %#08x" [expr {$a & $b}]] |
puts [format "a and b: %#08x" [expr {$a & $b}]] |
||
puts [format "a or b: %#08x" [expr {$a | $b}]] |
puts [format "a or b: %#08x" [expr {$a | $b}]] |
||
Line 5,849: | Line 5,849: | ||
puts [format "a << b: %#08x" [expr {$a << $b}]] |
puts [format "a << b: %#08x" [expr {$a << $b}]] |
||
puts [format "a >> b: %#08x" [expr {$a >> $b}]] |
puts [format "a >> b: %#08x" [expr {$a >> $b}]] |
||
}</ |
}</syntaxhighlight> |
||
There are no built-in operations for arithmetic right shift or for bit rotation. Indeed, rotation precludes the use of arbitrary-width integers and can only be defined with respect to a particular width. However, we can simulate these operations for 32-bit values (requires Tcl 8.5): |
There are no built-in operations for arithmetic right shift or for bit rotation. Indeed, rotation precludes the use of arbitrary-width integers and can only be defined with respect to a particular width. However, we can simulate these operations for 32-bit values (requires Tcl 8.5): |
||
< |
<syntaxhighlight lang=tcl>proc bitwiseUnsupported {a b} { |
||
set bits 0xFFFFFFFF |
set bits 0xFFFFFFFF |
||
# Force interpretation as a 32-bit unsigned value |
# Force interpretation as a 32-bit unsigned value |
||
Line 5,863: | Line 5,863: | ||
(($a >> (32-$b)) & ($bits ^ ($bits << $b))) |
(($a >> (32-$b)) & ($bits ^ ($bits << $b))) |
||
}]] |
}]] |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
Line 5,871: | Line 5,871: | ||
The right shift operation fills the new leftmost bit with a copy of the old leftmost bit. |
The right shift operation fills the new leftmost bit with a copy of the old leftmost bit. |
||
< |
<syntaxhighlight lang=ti89b>bitwise(a,b) |
||
Prgm |
Prgm |
||
Local show, oldbase |
Local show, oldbase |
||
Line 5,893: | Line 5,893: | ||
show("RRo ", rotate(a,–b)) |
show("RRo ", rotate(a,–b)) |
||
setMode("Base",oldbase) |
setMode("Base",oldbase) |
||
EndPrgm</ |
EndPrgm</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang=Vala>void testbit(int a, int b) { |
||
print(@"input: a = $a, b = $b\n"); |
print(@"input: a = $a, b = $b\n"); |
||
print(@"AND: $a & $b = $(a & b)\n"); |
print(@"AND: $a & $b = $(a & b)\n"); |
||
Line 5,912: | Line 5,912: | ||
int b = 2; |
int b = 2; |
||
testbit(a,b); |
testbit(a,b); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>input: a = 255, b = 2 |
<pre>input: a = 255, b = 2 |
||
Line 5,926: | Line 5,926: | ||
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"). |
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 Or &HFF00) 'FFF0 |
||
Debug.Print Hex(&HF0F0 Xor &HFF00) 'FF0 |
Debug.Print Hex(&HF0F0 Xor &HFF00) 'FF0 |
||
Line 5,932: | Line 5,932: | ||
Debug.Print Hex(&HF0F0 Eqv &HFF00) 'F00F |
Debug.Print Hex(&HF0F0 Eqv &HFF00) 'F00F |
||
Debug.Print Hex(&HF0F0 Imp &HFF00) 'FF0F |
Debug.Print Hex(&HF0F0 Imp &HFF00) 'FF0F |
||
</syntaxhighlight> |
|||
</lang> |
|||
The other operations in the task are not builtin, but are easy to implement. Integers are signed, and overflow throws and exception, one must take care of this. |
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 |
If k < 1 Then |
||
MaskL = 0 |
MaskL = 0 |
||
Line 6,014: | Line 6,014: | ||
Function TestBit(n As Long, k As Integer) As Boolean |
Function TestBit(n As Long, k As Integer) As Boolean |
||
TestBit = (n And Bit(k)) <> 0 |
TestBit = (n And Bit(k)) <> 0 |
||
End Function</ |
End Function</syntaxhighlight> |
||
Examples |
Examples |
||
< |
<syntaxhighlight lang=vb>Debug.Print Hex(MaskL(8)) 'FF000000 |
||
Debug.Print Hex(MaskR(8)) 'FF |
Debug.Print Hex(MaskR(8)) 'FF |
||
Debug.Print Hex(Bit(7)) '80 |
Debug.Print Hex(Bit(7)) '80 |
||
Line 6,029: | Line 6,029: | ||
Debug.Print Hex(RotateR(65535, 8)) 'FF0000FF |
Debug.Print Hex(RotateR(65535, 8)) 'FF0000FF |
||
Debug.Print Hex(RotateR(65535, -8)) 'FFFF00 |
Debug.Print Hex(RotateR(65535, -8)) 'FFFF00 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Visual Basic}}== |
=={{header|Visual Basic}}== |
||
Line 6,036: | Line 6,036: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
< |
<syntaxhighlight lang=vbnet>Sub Test(a as Integer, b as Integer) |
||
WriteLine("And " & a And b) |
WriteLine("And " & a And b) |
||
WriteLine("Or " & a Or b) |
WriteLine("Or " & a Or b) |
||
Line 6,043: | Line 6,043: | ||
WriteLine("Left Shift " & a << 2) |
WriteLine("Left Shift " & a << 2) |
||
WriteLine("Right Shift " & a >> 2) |
WriteLine("Right Shift " & a >> 2) |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
Visual Basic doesn't have built-in support for bitwise rotation. |
Visual Basic doesn't have built-in support for bitwise rotation. |
||
Line 6,055: | Line 6,055: | ||
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. |
Given this limitation, there is no difference between logical and arithmetic left and right shift operations. Although Wren doesn't support circular shift operators, it is not difficult to write functions to perform them. |
||
< |
<syntaxhighlight lang=ecmascript>var rl = Fn.new { |x, y| x << y | x >> (32-y) } |
||
var rr = Fn.new { |x, y| x >> y | x << (32-y) } |
var rr = Fn.new { |x, y| x >> y | x << (32-y) } |
||
Line 6,075: | Line 6,075: | ||
} |
} |
||
bitwise.call(10, 2)</ |
bitwise.call(10, 2)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,094: | Line 6,094: | ||
{{works with|nasm}} |
{{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) |
It must be linked with the libc and "start" code; lazyly a <tt>gcc bitops.o</tt> works, being bitops.o produced by <tt>nasm -f elf bitops.asm</tt> (I've chosen ELF since I am on a GNU/Linux box) |
||
< |
<syntaxhighlight lang=asm> extern printf |
||
global main |
global main |
||
Line 6,197: | Line 6,197: | ||
_null db 0 |
_null db 0 |
||
end</ |
end</syntaxhighlight> |
||
=={{header|XBasic}}== |
=={{header|XBasic}}== |
||
{{works with|Windows XBasic}} |
{{works with|Windows XBasic}} |
||
< |
<syntaxhighlight lang=xbasic> |
||
PROGRAM "bitwise" |
PROGRAM "bitwise" |
||
Line 6,243: | Line 6,243: | ||
END FUNCTION |
END FUNCTION |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,270: | Line 6,270: | ||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
< |
<syntaxhighlight lang=lisp>(defun bitwise-operations (a b) |
||
; rotate operations are not supported |
; rotate operations are not supported |
||
(print `(,a and ,b = ,(logand a b))) |
(print `(,a and ,b = ,(logand a b))) |
||
Line 6,277: | Line 6,277: | ||
(print `(,a left shift by ,b = ,(lsh 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 right shift by ,b = ,(lsh a (- b)))) ; negative second operand shifts right |
||
(print `(,a arithmetic right shift by ,b = ,(ash a (- b)))) )</ |
(print `(,a arithmetic right shift by ,b = ,(ash a (- b)))) )</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang=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 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: | |
Text(0, "A xor B = "); HexOut(0, A xor B); CrLf(0); \alternate symbol: | |
||
Line 6,291: | Line 6,291: | ||
func ROR(A, B); int A, B; return A>>B ! A<<(32-B); |
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);</ |
Text(0, "A ror B = "); HexOut(0, ROR(A,B)); CrLf(0);</syntaxhighlight> |
||
The reason the "!" and "|" symbols may seem reversed is that the OR |
The reason the "!" and "|" symbols may seem reversed is that the OR |
||
Line 6,298: | Line 6,298: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang=Yabasic>sub formBin$(n) |
||
return right$("00000000" + bin$(n), 8) |
return right$("00000000" + bin$(n), 8) |
||
end sub |
end sub |
||
Line 6,309: | Line 6,309: | ||
print "OR = \t", formBin$(or(a, b)) |
print "OR = \t", formBin$(or(a, b)) |
||
print "XOR = \t", formBin$(xor(a, b)) |
print "XOR = \t", formBin$(xor(a, b)) |
||
print "NOT ", a, " =\t", formBin$(xor(255, a))</ |
print "NOT ", a, " =\t", formBin$(xor(255, a))</syntaxhighlight> |
||
<pre>6 = 00000110 |
<pre>6 = 00000110 |
||
3 = 00000011 |
3 = 00000011 |
||
Line 6,320: | Line 6,320: | ||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |
||
;AND |
;AND |
||
< |
<syntaxhighlight lang=z80>LD A,&05 |
||
AND &1F ;0x05 & 0x1F</ |
AND &1F ;0x05 & 0x1F</syntaxhighlight> |
||
;OR |
;OR |
||
< |
<syntaxhighlight lang=z80>LD A,&05 |
||
OR &1F ;0x05 | 0x1F</ |
OR &1F ;0x05 | 0x1F</syntaxhighlight> |
||
;XOR |
;XOR |
||
< |
<syntaxhighlight lang=z80>LD A,&05 |
||
XOR &1F ;0x05 ^ 0x1F</ |
XOR &1F ;0x05 ^ 0x1F</syntaxhighlight> |
||
;NOT |
;NOT |
||
< |
<syntaxhighlight lang=z80>LD A,&05 |
||
CPL</ |
CPL</syntaxhighlight> |
||
;Left Shift (Z80 can only shift by one at a time.) |
;Left Shift (Z80 can only shift by one at a time.) |
||
< |
<syntaxhighlight lang=z80>LD A,&05 |
||
SLA A</ |
SLA A</syntaxhighlight> |
||
;Right Shift |
;Right Shift |
||
< |
<syntaxhighlight lang=z80>LD A,&05 |
||
SRL A</ |
SRL A</syntaxhighlight> |
||
;Arithmetic Right Shift |
;Arithmetic Right Shift |
||
< |
<syntaxhighlight lang=z80>LD A,&05 |
||
SRA A</ |
SRA A</syntaxhighlight> |
||
Z80 has two different types of bit rotates. |
Z80 has two different types of bit rotates. |
||
Line 6,351: | Line 6,351: | ||
* <code>RLC/RRC</code> copies the bit "pushed out" to the carry but the old carry isn't rotated in. |
* <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 |
RLA |
||
Line 6,361: | Line 6,361: | ||
LD A,&05 |
LD A,&05 |
||
RRCA</ |
RRCA</syntaxhighlight> |
||
Line 6,367: | Line 6,367: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
No bitwise rotates. Shifts are unsigned. |
No bitwise rotates. Shifts are unsigned. |
||
< |
<syntaxhighlight lang=zkl>(7).bitAnd(1) //-->1 |
||
(8).bitOr(1) //-->9 |
(8).bitOr(1) //-->9 |
||
(7).bitXor(1) //-->6 |
(7).bitXor(1) //-->6 |
||
Line 6,374: | Line 6,374: | ||
(7).shiftLeft(1) //-->0xe |
(7).shiftLeft(1) //-->0xe |
||
(-1).toString(16) //-->ffffffffffffffff |
(-1).toString(16) //-->ffffffffffffffff |
||
(-1).shiftRight(1).toString(16) //-->7fffffffffffffff</ |
(-1).shiftRight(1).toString(16) //-->7fffffffffffffff</syntaxhighlight> |
||