Bitwise operations: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
Thundergnat (talk | contribs) m (Automated syntax highlighting fixup (second round - minor fixes)) |
||
Line 9: | Line 9: | ||
If any operation is not available in your language, note it. |
If any operation is not available in your language, note it. |
||
<br><br> |
<br><br> |
||
=={{header|11l}}== |
=={{header|11l}}== |
||
{{trans|Kotlin}} |
{{trans|Kotlin}} |
||
<syntaxhighlight lang=11l>V x = 10 |
<syntaxhighlight lang="11l">V x = 10 |
||
V y = 2 |
V y = 2 |
||
print(‘x = ’x) |
print(‘x = ’x) |
||
Line 37: | Line 36: | ||
x ROR y = -2147483646 |
x ROR y = -2147483646 |
||
</pre> |
</pre> |
||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
<syntaxhighlight lang=360asm>* Bitwise operations 15/02/2017 |
<syntaxhighlight lang="360asm">* Bitwise operations 15/02/2017 |
||
BITWISE CSECT |
BITWISE CSECT |
||
USING BITWISE,R13 |
USING BITWISE,R13 |
||
Line 138: | Line 136: | ||
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 |
<syntaxhighlight lang="6502asm">LDA #$05 |
||
STA temp ;temp equals 5 for the following</syntaxhighlight> |
STA temp ;temp equals 5 for the following</syntaxhighlight> |
||
;AND |
;AND |
||
<syntaxhighlight lang=6502asm>LDA #$08 |
<syntaxhighlight lang="6502asm">LDA #$08 |
||
AND temp</syntaxhighlight> |
AND temp</syntaxhighlight> |
||
;OR |
;OR |
||
<syntaxhighlight lang=6502asm>LDA #$08 |
<syntaxhighlight lang="6502asm">LDA #$08 |
||
ORA temp</syntaxhighlight> |
ORA temp</syntaxhighlight> |
||
;XOR |
;XOR |
||
<syntaxhighlight lang=6502asm>LDA #$08 |
<syntaxhighlight lang="6502asm">LDA #$08 |
||
EOR temp</syntaxhighlight> |
EOR temp</syntaxhighlight> |
||
;NOT |
;NOT |
||
<syntaxhighlight lang=6502asm>LDA #$08 |
<syntaxhighlight lang="6502asm">LDA #$08 |
||
EOR #255</syntaxhighlight> |
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 |
<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 |
||
Line 167: | Line 165: | ||
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 |
<syntaxhighlight lang="6502asm">LDA #$01 |
||
ROL ;if the carry was set prior to the ROL, A = 3. If the carry was clear, A = 2.</syntaxhighlight> |
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 |
<syntaxhighlight lang="6502asm">LDA #$01 |
||
ROR ;if the carry was set prior to the ROR, A = 0x80. If clear, A = 0.</syntaxhighlight> |
ROR ;if the carry was set prior to the ROR, A = 0x80. If clear, A = 0.</syntaxhighlight> |
||
=={{header|68000 Assembly}}== |
|||
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation. |
|||
;AND |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0 |
|||
MOVE.W #$200,D1 |
|||
AND.W D0,D1</syntaxhighlight> |
|||
;OR |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0 |
|||
MOVE.W #$200,D1 |
|||
OR.W D0,D1</syntaxhighlight> |
|||
;XOR |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0 |
|||
MOVE.W #$200,D1 |
|||
EOR.W D0,D1</syntaxhighlight> |
|||
;NOT |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$100,D0 |
|||
NOT.W D0</syntaxhighlight> |
|||
;Left Shift |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$FF,D0 |
|||
MOVE.W #$04,D1 |
|||
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</syntaxhighlight> |
|||
;Right Shift |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$FF,D0 |
|||
MOVE.W #$04,D1 |
|||
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</syntaxhighlight> |
|||
;Arithmetic Right Shift |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</syntaxhighlight> |
|||
;Left Rotate |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ROL.W D1,D0</syntaxhighlight> |
|||
;Right Rotate |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ROR.W D1,D0</syntaxhighlight> |
|||
;Left Rotate Through Extend Flag |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ROXL.W D1,D0</syntaxhighlight> |
|||
;Right Rotate Through Extend Flag |
|||
<syntaxhighlight lang=68000devpac>MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ROXR.W D1,D0</syntaxhighlight> |
|||
=={{header|8051 Assembly}}== |
=={{header|8051 Assembly}}== |
||
Integer one is assumed to be a, integer two assumed to be b. |
Integer one is assumed to be a, integer two assumed to be b. |
||
Line 234: | Line 175: | ||
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 |
<syntaxhighlight lang="asm">; bitwise AND |
||
anl a, b |
anl a, b |
||
Line 286: | Line 227: | ||
rr a |
rr a |
||
djnz b, loop</syntaxhighlight> |
djnz b, loop</syntaxhighlight> |
||
=={{header|8086 Assembly}}== |
=={{header|8086 Assembly}}== |
||
;AND |
;AND |
||
<syntaxhighlight lang=asm>MOV AX,0345h |
<syntaxhighlight lang="asm">MOV AX,0345h |
||
MOV BX,0444h |
MOV BX,0444h |
||
AND AX,BX</syntaxhighlight> |
AND AX,BX</syntaxhighlight> |
||
;OR |
;OR |
||
<syntaxhighlight lang=asm>MOV AX,0345h |
<syntaxhighlight lang="asm">MOV AX,0345h |
||
MOV BX,0444h |
MOV BX,0444h |
||
OR AX,BX</syntaxhighlight> |
OR AX,BX</syntaxhighlight> |
||
;XOR |
;XOR |
||
<syntaxhighlight lang=asm>MOV AX,0345h |
<syntaxhighlight lang="asm">MOV AX,0345h |
||
MOV BX,0444h |
MOV BX,0444h |
||
XOR AX,BX</syntaxhighlight> |
XOR AX,BX</syntaxhighlight> |
||
;NOT |
;NOT |
||
<syntaxhighlight lang=asm>MOV AX,0345h |
<syntaxhighlight lang="asm">MOV AX,0345h |
||
NOT AX</syntaxhighlight> |
NOT AX</syntaxhighlight> |
||
;Left Shift |
;Left Shift |
||
<syntaxhighlight lang=asm>MOV AX,03h |
<syntaxhighlight lang="asm">MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
SHL AX,CL</syntaxhighlight> |
SHL AX,CL</syntaxhighlight> |
||
;Right Shift |
;Right Shift |
||
<syntaxhighlight lang=asm>MOV AX,03h |
<syntaxhighlight lang="asm">MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
SHR AX,CL</syntaxhighlight> |
SHR AX,CL</syntaxhighlight> |
||
;Arithmetic Right Shift |
;Arithmetic Right Shift |
||
<syntaxhighlight lang=asm>MOV AX,03h |
<syntaxhighlight lang="asm">MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
SAR AX,CL</syntaxhighlight> |
SAR AX,CL</syntaxhighlight> |
||
;Left Rotate |
;Left Rotate |
||
<syntaxhighlight lang=asm>MOV AX,03h |
<syntaxhighlight lang="asm">MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
ROL AX,CL</syntaxhighlight> |
ROL AX,CL</syntaxhighlight> |
||
;Right Rotate |
;Right Rotate |
||
<syntaxhighlight lang=asm>MOV AX,03h |
<syntaxhighlight lang="asm">MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
ROR AX,CL</syntaxhighlight> |
ROR AX,CL</syntaxhighlight> |
||
;Left Rotate Through Carry |
;Left Rotate Through Carry |
||
<syntaxhighlight lang=asm>MOV AX,03h |
<syntaxhighlight lang="asm">MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
RCL AX,CL</syntaxhighlight> |
RCL AX,CL</syntaxhighlight> |
||
;Right Rotate Through Carry |
;Right Rotate Through Carry |
||
<syntaxhighlight lang=asm>MOV AX,03h |
<syntaxhighlight lang="asm">MOV AX,03h |
||
MOV CL,02h |
MOV CL,02h |
||
RCR AX,CL</syntaxhighlight> |
RCR AX,CL</syntaxhighlight> |
||
=={{header|68000 Assembly}}== |
|||
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation. |
|||
;AND |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0 |
|||
MOVE.W #$200,D1 |
|||
AND.W D0,D1</syntaxhighlight> |
|||
;OR |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0 |
|||
MOVE.W #$200,D1 |
|||
OR.W D0,D1</syntaxhighlight> |
|||
;XOR |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0 |
|||
MOVE.W #$200,D1 |
|||
EOR.W D0,D1</syntaxhighlight> |
|||
;NOT |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$100,D0 |
|||
NOT.W D0</syntaxhighlight> |
|||
;Left Shift |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$FF,D0 |
|||
MOVE.W #$04,D1 |
|||
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</syntaxhighlight> |
|||
;Right Shift |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$FF,D0 |
|||
MOVE.W #$04,D1 |
|||
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</syntaxhighlight> |
|||
;Arithmetic Right Shift |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</syntaxhighlight> |
|||
;Left Rotate |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ROL.W D1,D0</syntaxhighlight> |
|||
;Right Rotate |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ROR.W D1,D0</syntaxhighlight> |
|||
;Left Rotate Through Extend Flag |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ROXL.W D1,D0</syntaxhighlight> |
|||
;Right Rotate Through Extend Flag |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #$FF00,D0 |
|||
MOVE.W #$04,D1 |
|||
ROXR.W D1,D0</syntaxhighlight> |
|||
=={{header|ABAP}}== |
=={{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= |
<syntaxhighlight lang="abap"> |
||
report z_bitwise_operations. |
report z_bitwise_operations. |
||
Line 639: | Line 633: | ||
a rotr b -> C000003F, 11000000000000000000000000111111, -1073741761 |
a rotr b -> C000003F, 11000000000000000000000000111111, -1073741761 |
||
</pre> |
</pre> |
||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
Unlisted operations are not available |
Unlisted operations are not available |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="lisp">(defun bitwise (a b) |
||
(list (logand a b) |
(list (logand a b) |
||
(logior a b) |
(logior a b) |
||
Line 649: | Line 642: | ||
(ash a b) |
(ash a b) |
||
(ash a (- b))))</syntaxhighlight> |
(ash a (- b))))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="action!">BYTE FUNC Not(BYTE a) |
||
RETURN (a!$FF) |
RETURN (a!$FF) |
||
Line 685: | Line 677: | ||
127 SHL 2 = 252 |
127 SHL 2 = 252 |
||
</pre> |
</pre> |
||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
ActionScript does not support bitwise rotations. |
ActionScript does not support bitwise rotations. |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="actionscript">function bitwise(a:int, b:int):void |
||
{ |
{ |
||
trace("And: ", a & b); |
trace("And: ", a & b); |
||
Line 698: | Line 689: | ||
trace("Right Shift(Logical): ", a >>> b); |
trace("Right Shift(Logical): ", a >>> b); |
||
}</syntaxhighlight> |
}</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; |
<syntaxhighlight lang="ada">with Ada.Text_IO, Interfaces; |
||
use Ada.Text_IO, Interfaces; |
use Ada.Text_IO, Interfaces; |
||
Line 725: | Line 715: | ||
Put_Line (Unsigned_8'Image (Rotate_Right (X, N))); |
Put_Line (Unsigned_8'Image (Rotate_Right (X, N))); |
||
end Bitwise;</syntaxhighlight> |
end Bitwise;</syntaxhighlight> |
||
=={{header|Aikido}}== |
=={{header|Aikido}}== |
||
{{trans|Javascript}} |
{{trans|Javascript}} |
||
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){ |
<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 739: | Line 728: | ||
println("a >>> b: " + (a >>> b)) // logical right shift |
println("a >>> b: " + (a >>> b)) // logical right shift |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68|Standard - no extensions to language used}} |
{{works with|ALGOL 68|Standard - no extensions to language used}} |
||
Line 747: | Line 735: | ||
* 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:( |
<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 836: | Line 824: | ||
</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 # |
<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 854: | Line 842: | ||
+85, 8r0125, FTFTFTFT |
+85, 8r0125, FTFTFTFT |
||
</pre> |
</pre> |
||
=={{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 % |
<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 875: | Line 862: | ||
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" ) |
write( n1, " shr ", n2, " = ", number( b1 shr n2 ), " ( right-shift )" ) |
||
end bitOPerations ;</syntaxhighlight> |
end bitOPerations ;</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
Applescript has no bitwise operators. It's probably not the right tool to reach for if you need to work with bits. |
Applescript has no bitwise operators. It's probably not the right tool to reach for if you need to work with bits. |
||
Line 893: | Line 879: | ||
<syntaxhighlight lang=applescript>use AppleScript version "2.4" |
<syntaxhighlight lang="applescript">use AppleScript version "2.4" |
||
use framework "Foundation" |
use framework "Foundation" |
||
use scripting additions |
use scripting additions |
||
Line 1,264: | Line 1,250: | ||
'''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" |
<syntaxhighlight lang="applescript">use AppleScript version "2.4" |
||
use framework "Foundation" |
use framework "Foundation" |
||
use scripting additions |
use scripting additions |
||
Line 1,771: | Line 1,757: | ||
A '''third option''' is the mathematical one, although it still involves looping through the hypothetical bits where two numbers are involved, unless I've missed a trick. The handlers below all assume positive number inputs (except for ''arithmeticRightShift()'') and attempt to return results of class integer. The "hi bits" of numbers which don't fit the specified register sizes are discarded. |
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) |
<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,853: | Line 1,839: | ||
rightRotate(92, 7, 8) --> 184 |
rightRotate(92, 7, 8) --> 184 |
||
rightRotate(92, 7, 16) --> 47104</syntaxhighlight> |
rightRotate(92, 7, 16) --> 47104</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="arm assembly"> |
||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
Line 2,019: | Line 2,004: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
<syntaxhighlight lang=rebol>a: 255 |
<syntaxhighlight lang="rebol">a: 255 |
||
b: 2 |
b: 2 |
||
Line 2,039: | Line 2,023: | ||
255 SHL 2 = 1020 |
255 SHL 2 = 1020 |
||
255 SHR 2 = 63 </pre> |
255 SHR 2 = 63 </pre> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="autohotkey">bitwise(3, 4) |
||
bitwise(a, b) |
bitwise(a, b) |
||
{ |
{ |
||
Line 2,051: | Line 2,034: | ||
MsgBox % "a >> b: " . a >> b ; arithmetic right shift |
MsgBox % "a >> b: " . a >> b ; arithmetic right shift |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
No arithmetic shift. |
No arithmetic shift. |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="autoit">bitwise(255, 5) |
||
Func bitwise($a, $b) |
Func bitwise($a, $b) |
||
MsgBox(1, '', _ |
MsgBox(1, '', _ |
||
Line 2,077: | Line 2,059: | ||
255 ROL 5: 8160 |
255 ROL 5: 8160 |
||
255 ROR 5: 63495</pre> |
255 ROR 5: 63495</pre> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Standard awk does not have bitwise operators. Gawk has built-in functions for many bitwise operations. No rotation of bits. |
Standard awk does not have bitwise operators. Gawk has built-in functions for many bitwise operations. No rotation of bits. |
||
Line 2,083: | Line 2,064: | ||
{{works with|gawk}} |
{{works with|gawk}} |
||
<syntaxhighlight lang=awk>BEGIN { |
<syntaxhighlight lang="awk">BEGIN { |
||
n = 11 |
n = 11 |
||
p = 1 |
p = 1 |
||
Line 2,095: | Line 2,076: | ||
[[OpenBSD]] <code>/usr/bin/awk</code> (a variant of [[nawk]]) has these same functions, with a few differences. Gawk uses 53-bit unsigned integers, but OpenBSD awk uses 32-bit signed integers. Therefore Gawk prints <code>not 11 = 0x1ffffffffffff4</code>, but OpenBSD awk prints <code>not 11 = 0xfffffff4</code>. |
[[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 |
<syntaxhighlight lang="axe">Lbl BITS |
||
r₁→A |
r₁→A |
||
r₂→B |
r₂→B |
||
Line 2,108: | Line 2,088: | ||
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. |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
In Babel, we prefix the logic operators with a 'c' to denote that they are C-style operations, that is, they are word-width operations, not arbitrary size operations. The following program combines the numbers 5 and 9 using the various bitwise operators and then displays the results. |
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> |
<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,107: | ||
The cnot operator works on just one operand: |
The cnot operator works on just one operand: |
||
<syntaxhighlight lang=babel>9 cnot ;</syntaxhighlight> |
<syntaxhighlight lang="babel">9 cnot ;</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[val 0xfffffff6 ]</pre> |
<pre>[val 0xfffffff6 ]</pre> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{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) |
<syntaxhighlight lang="qbasic">SUB bitwise (a, b) |
||
PRINT a AND b |
PRINT a AND b |
||
PRINT a OR b |
PRINT a OR b |
||
Line 2,145: | Line 2,123: | ||
{{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) |
<syntaxhighlight lang="freebasic">SUB bitwise (a AS Integer, b AS Integer) |
||
DIM u AS UInteger |
DIM u AS UInteger |
||
Line 2,161: | Line 2,139: | ||
Commodore BASIC V2.0 does not have '''XOR''', '''left shift''', '''right shift''', '''right arithmetic shift''', '''left rotate''', and '''right rotate''' operators. In this implementation the '''XOR''' operation is done with an equivalent formula. |
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 |
<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 |
||
Line 2,178: | Line 2,156: | ||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
<syntaxhighlight lang= |
<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,193: | Line 2,171: | ||
The disassembly of the Z80 code would be: |
The disassembly of the Z80 code would be: |
||
<syntaxhighlight lang=z80asm> org 4084 |
<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,208: | Line 2,186: | ||
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 |
<syntaxhighlight lang="basic"> 10 REM ABCDEFGHIJKLMNO |
||
20 INPUT A |
20 INPUT A |
||
30 INPUT B |
30 INPUT B |
||
Line 2,246: | Line 2,224: | ||
Tiny BASIC has only one data type- the signed 16-bit integer- and no bitwise operations. This code emulates bitwise operations on unsigned 15-bit integers. Since the logic gates AND, NOR, and NXOR are characterised by having exactly two, exactly zero, and exactly one on bit in their inputs, their code is identical except for having a different number of target on bits (line 500 onward). The OR and XOR gates are just NOT NOR and NOT NXOR. The shift and rotate operations are simple divisions and mutiplications by 2, with care taken to avoid overflow, and a carry flag where applicable. |
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> |
<syntaxhighlight lang="tinybasic"> |
||
REM VARIABLES |
REM VARIABLES |
||
REM A = first number |
REM A = first number |
||
Line 2,327: | Line 2,305: | ||
GOTO 500 |
GOTO 500 |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="basic256"># bitwise operators - floating point numbers will be cast to integer |
||
a = 0b00010001 |
a = 0b00010001 |
||
b = 0b11110000 |
b = 0b11110000 |
||
Line 2,337: | Line 2,314: | ||
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> |
print a & b # bitwise or on two integer values</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
The SET command with the /A option supports arithmetic and bit operations on signed 8 byte integers. |
The SET command with the /A option supports arithmetic and bit operations on signed 8 byte integers. |
||
Line 2,344: | Line 2,320: | ||
The following script (bitops.bat) not only demonstrates the basic bit operations, it also uses bit operations to convert each integral value into a string of 32 binary digits. |
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> |
<syntaxhighlight lang="dos"> |
||
@echo off |
@echo off |
||
setlocal |
setlocal |
||
Line 2,463: | Line 2,439: | ||
11111101000000000000000000000001 |
11111101000000000000000000000001 |
||
</pre> |
</pre> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
<syntaxhighlight lang=bbcbasic> number1% = &89ABCDEF |
<syntaxhighlight lang="bbcbasic"> number1% = &89ABCDEF |
||
number2% = 8 |
number2% = 8 |
||
Line 2,477: | Line 2,452: | ||
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</syntaxhighlight> |
PRINT ~ (number1% >>> number2%) OR (number1% << (32-number2%)) : REM right rotate</syntaxhighlight> |
||
=={{header|beeswax}}== |
=={{header|beeswax}}== |
||
<syntaxhighlight lang=beeswax>#eX~T~T_# |
<syntaxhighlight lang="beeswax">#eX~T~T_# |
||
###>N{` AND `~{~` = `&{Nz1~3J |
###>N{` AND `~{~` = `&{Nz1~3J |
||
UXe# |
UXe# |
||
Line 2,506: | Line 2,480: | ||
Example: |
Example: |
||
<syntaxhighlight lang= |
<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,530: | Line 2,504: | ||
Arithmetic shift right is not originally implemented in beeswax because it does not make sense for unsigned integers, but for negative numbers, it can be realized easily with |
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> |
<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) |
<syntaxhighlight lang="beeswax">A ROL B = A<<(B%64)+A>>>(64-B%64) |
||
A ROR B = A>>>(B%64)+A<<(64-B%64)</syntaxhighlight> |
A ROR B = A>>>(B%64)+A<<(64-B%64)</syntaxhighlight> |
||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
<syntaxhighlight lang=befunge>> v MCR >v |
<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,590: | Line 2,563: | ||
1 22 23 106 42 10 |
1 22 23 106 42 10 |
||
</pre> |
</pre> |
||
=={{header|C}}== |
=={{header|C}}== |
||
<syntaxhighlight lang=c>void bitwise(int a, int b) |
<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,608: | Line 2,580: | ||
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= |
<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= |
}</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</syntaxhighlight> |
ret</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
<syntaxhighlight lang=csharp>static void bitwise(int a, int b) |
<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,633: | Line 2,604: | ||
// there are no rotation operators in C# |
// there are no rotation operators in C# |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{trans|C}} |
{{trans|C}} |
||
<syntaxhighlight lang=cpp>#include <iostream> |
<syntaxhighlight lang="cpp">#include <iostream> |
||
void bitwise(int a, int b) |
void bitwise(int a, int b) |
||
Line 2,659: | Line 2,629: | ||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
<syntaxhighlight lang=lisp>(bit-and x y) |
<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,668: | Line 2,637: | ||
(bit-shift-right x n) |
(bit-shift-right x n) |
||
;;There is no built-in for rotation.</syntaxhighlight> |
;;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. |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. bitwise-ops. |
PROGRAM-ID. bitwise-ops. |
||
Line 2,708: | Line 2,676: | ||
{{works with|Visual COBOL}} |
{{works with|Visual COBOL}} |
||
<syntaxhighlight lang=cobol> IDENTIFICATION DIVISION. |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. mf-bitwise-ops. |
PROGRAM-ID. mf-bitwise-ops. |
||
Line 2,749: | Line 2,717: | ||
GOBACK |
GOBACK |
||
.</syntaxhighlight> |
.</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> |
<syntaxhighlight lang="coffeescript"> |
||
f = (a, b) -> |
f = (a, b) -> |
||
p "and", a & b |
p "and", a & b |
||
Line 2,769: | Line 2,736: | ||
output |
output |
||
<syntaxhighlight lang=text> |
<syntaxhighlight lang="text"> |
||
> coffee foo.coffee |
> coffee foo.coffee |
||
and 2 |
and 2 |
||
Line 2,778: | Line 2,745: | ||
>> 2 |
>> 2 |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
<syntaxhighlight lang=lisp>(defun bitwise (a b) |
<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,792: | Line 2,758: | ||
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> |
<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,806: | Line 2,772: | ||
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> |
<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,821: | Line 2,787: | ||
(1- (ash 1 width))))) |
(1- (ash 1 width))))) |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
<syntaxhighlight lang=d>T rot(T)(in T x, in int shift) pure nothrow @nogc { |
<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,857: | Line 2,822: | ||
Compilers are usually able to optimize the code pattern of the rot function to one CPU instruction plus loads. The DMD compiler too performs such optimization. |
Compilers are usually able to optimize the code pattern of the rot function to one CPU instruction plus loads. The DMD compiler too performs such optimization. |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="delphi">program Bitwise; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 2,873: | Line 2,837: | ||
Readln; |
Readln; |
||
end.</syntaxhighlight> |
end.</syntaxhighlight> |
||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
<syntaxhighlight lang= |
<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)); |
||
Line 2,881: | Line 2,844: | ||
PrintLn('2 shl 3 = '+IntToStr(2 shl 3)); |
PrintLn('2 shl 3 = '+IntToStr(2 shl 3)); |
||
PrintLn('2 shr 3 = '+IntToStr(2 shr 3));</syntaxhighlight> |
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) { |
<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,895: | Line 2,857: | ||
`) |
`) |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="ecl"> |
||
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION |
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION |
||
BitAND := A & B; |
BitAND := A & B; |
||
Line 2,928: | Line 2,889: | ||
*/ |
*/ |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x : |
ELENA 4.x : |
||
<syntaxhighlight lang=elena>import extensions; |
<syntaxhighlight lang="elena">import extensions; |
||
extension testOp |
extension testOp |
||
Line 2,959: | Line 2,919: | ||
255 shl 2 = 1020 |
255 shl 2 = 1020 |
||
</pre> |
</pre> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
<syntaxhighlight lang=elixir>defmodule Bitwise_operation do |
<syntaxhighlight lang="elixir">defmodule Bitwise_operation do |
||
use Bitwise |
use Bitwise |
||
Line 3,002: | Line 2,961: | ||
255 >>> 2 = 63 |
255 >>> 2 = 63 |
||
</pre> |
</pre> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
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> |
<syntaxhighlight lang="erlang"> |
||
-module(bitwise_operations). |
-module(bitwise_operations). |
||
Line 3,023: | Line 2,981: | ||
outputs: |
outputs: |
||
<syntaxhighlight lang=erlang> |
<syntaxhighlight lang="erlang"> |
||
255 band 170 = 170 |
255 band 170 = 170 |
||
255 bor 170 = 255 |
255 bor 170 = 255 |
||
Line 3,031: | Line 2,989: | ||
255 bsr 170 = 0 |
255 bsr 170 = 0 |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
<syntaxhighlight lang=fsharp>let bitwise a b = |
<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,042: | Line 2,999: | ||
printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift |
printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift |
||
// No rotation operators.</syntaxhighlight> |
// No rotation operators.</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
<syntaxhighlight lang=factor>"a=" "b=" [ write readln string>number ] bi@ |
<syntaxhighlight lang="factor">"a=" "b=" [ write readln string>number ] bi@ |
||
{ |
{ |
||
[ bitand "a AND b: " write . ] |
[ bitand "a AND b: " write . ] |
||
Line 3,055: | Line 3,011: | ||
outputs: |
outputs: |
||
<syntaxhighlight lang=factor>a=255 |
<syntaxhighlight lang="factor">a=255 |
||
b=5 |
b=5 |
||
a AND b: 5 |
a AND b: 5 |
||
Line 3,064: | Line 3,020: | ||
a asr b: 7</syntaxhighlight> |
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 |
<syntaxhighlight lang="false">10 3 |
||
\$@$@$@$@\ { 3 copies } |
\$@$@$@$@\ { 3 copies } |
||
"a & b = "&." |
"a & b = "&." |
||
Line 3,073: | Line 3,028: | ||
~a = "%~." |
~a = "%~." |
||
"</syntaxhighlight> |
"</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) |
<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,087: | Line 3,041: | ||
2drop ;</syntaxhighlight> |
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 |
<syntaxhighlight lang="fortran">integer :: i, j = -1, k = 42 |
||
logical :: a |
logical :: a |
||
Line 3,118: | Line 3,071: | ||
! arithmetically equivalent to: MOD((K / 2**7), 2**8)</syntaxhighlight> |
! 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"> 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> |
<syntaxhighlight lang="fortran"> |
||
program bits_rosetta |
program bits_rosetta |
||
implicit none |
implicit none |
||
Line 3,148: | Line 3,101: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
Output |
Output |
||
<syntaxhighlight lang=text> |
<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,158: | Line 3,111: | ||
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823 |
ROT : 00000000000000000000000000001110 ~ 00000000000000000000000000000011 = 11000000000000000000000000000001 -1073741823 |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Free Pascal}}== |
=={{header|Free Pascal}}== |
||
<syntaxhighlight lang=pascal>program Bitwise; |
<syntaxhighlight lang="pascal">program Bitwise; |
||
{$mode objfpc} |
{$mode objfpc} |
||
var |
var |
||
Line 3,179: | Line 3,131: | ||
Readln; |
Readln; |
||
end.</syntaxhighlight> |
end.</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
<syntaxhighlight lang=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,267: | Line 3,218: | ||
x ROR y = 4611686018427387902 |
x ROR y = 4611686018427387902 |
||
</pre> |
</pre> |
||
=={{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) |
<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,313: | Line 3,263: | ||
Rotate right : fn rotr( a, b ) = 11000000000000000000000000111111 : -1073741761 |
Rotate right : fn rotr( a, b ) = 11000000000000000000000000111111 : -1073741761 |
||
</pre> |
</pre> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
<syntaxhighlight lang=go>package main |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 3,366: | Line 3,315: | ||
rol: 1000110100111111 |
rol: 1000110100111111 |
||
ror: 1101001111111000</pre> |
ror: 1101001111111000</pre> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
<syntaxhighlight lang=groovy>def bitwise = { a, b -> |
<syntaxhighlight lang="groovy">def bitwise = { a, b -> |
||
println """ |
println """ |
||
a & b = ${a} & ${b} = ${a & b} |
a & b = ${a} & ${b} = ${a & b} |
||
Line 3,381: | Line 3,329: | ||
Program: |
Program: |
||
<syntaxhighlight lang=groovy>bitwise(-15,3)</syntaxhighlight> |
<syntaxhighlight lang="groovy">bitwise(-15,3)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,391: | Line 3,339: | ||
a >> b = -15 >> 3 = -2 arithmetic (sign-preserving) shift |
a >> b = -15 >> 3 = -2 arithmetic (sign-preserving) shift |
||
a >>> b = -15 >>> 3 = 536870910 logical (zero-filling) shift</pre> |
a >>> b = -15 >>> 3 = 536870910 logical (zero-filling) shift</pre> |
||
=={{header|Harbour}}== |
=={{header|Harbour}}== |
||
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> |
<syntaxhighlight lang="visualfoxpro"> |
||
PROCEDURE Main(...) |
PROCEDURE Main(...) |
||
local n1 := 42, n2 := 2 |
local n1 := 42, n2 := 2 |
||
Line 3,454: | Line 3,401: | ||
Rotate left --> 168 |
Rotate left --> 168 |
||
Rotate right --> -2147483638 |
Rotate right --> -2147483638 |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
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 |
<syntaxhighlight lang="haskell">import Data.Bits |
||
bitwise :: Int -> Int -> IO () |
bitwise :: Int -> Int -> IO () |
||
Line 3,500: | Line 3,446: | ||
print $ shiftL (-1 :: Word) 1 |
print $ shiftL (-1 :: Word) 1 |
||
print $ shiftR (-1 :: Word) 1 |
print $ shiftR (-1 :: Word) 1 |
||
=={{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) |
<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 )</syntaxhighlight> |
i = NOT( k )</syntaxhighlight> |
||
=={{header|HPPPL}}== |
=={{header|HPPPL}}== |
||
<syntaxhighlight lang=hpppl>EXPORT BITOPS(a, b) |
<syntaxhighlight lang="hpppl">EXPORT BITOPS(a, b) |
||
BEGIN |
BEGIN |
||
PRINT(BITAND(a, b)); |
PRINT(BITAND(a, b)); |
||
Line 3,519: | Line 3,463: | ||
// HPPPL has no builtin rotates or arithmetic right shift. |
// HPPPL has no builtin rotates or arithmetic right shift. |
||
END;</syntaxhighlight> |
END;</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="icon">procedure main() |
||
bitdemo(255,2) |
bitdemo(255,2) |
||
bitdemo(-15,3) |
bitdemo(-15,3) |
||
Line 3,565: | Line 3,508: | ||
i shift 3: -120 = -1111000b |
i shift 3: -120 = -1111000b |
||
i shift -3: -2 = -10b</pre> |
i shift -3: -2 = -10b</pre> |
||
=={{header|Inform 6}}== |
=={{header|Inform 6}}== |
||
Inform 6 has no xor or rotate operators. It also has no shift operators, although the Z-machine, its usual target architecture, does. These can be accessed with inline assembly, which is done here. |
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= |
<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,585: | Line 3,527: | ||
]; |
]; |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
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 |
<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,602: | Line 3,543: | ||
And here is a routine which takes a list of bitwise operators and two numbers and displays a table of results from combining those two numbers with each of the operators: |
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 |
<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 |
||
Line 3,609: | Line 3,550: | ||
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 |
<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,621: | Line 3,562: | ||
Further test |
Further test |
||
<syntaxhighlight lang=j> |
<syntaxhighlight lang="j"> |
||
bXOR/ 3333 5555 7777 9999 |
bXOR/ 3333 5555 7777 9999 |
||
8664 |
8664 |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
<syntaxhighlight lang=java>public static void bitwise(int a, int b){ |
<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,639: | Line 3,579: | ||
}</syntaxhighlight> |
}</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; |
<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;</syntaxhighlight> |
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){ |
<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,656: | Line 3,595: | ||
alert("a >>> b: " + (a >>> b)); // logical right shift |
alert("a >>> b: " + (a >>> b)); // logical right shift |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
<syntaxhighlight lang=julia># Version 5.2 |
<syntaxhighlight lang="julia"># Version 5.2 |
||
@show 1 & 2 # AND |
@show 1 & 2 # AND |
||
@show 1 | 2 # OR |
@show 1 | 2 # OR |
||
Line 3,689: | Line 3,627: | ||
rol(A,5) = Bool[true,true,false,false,true] |
rol(A,5) = Bool[true,true,false,false,true] |
||
</pre> |
</pre> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
<syntaxhighlight lang=scala>/* for symmetry with Kotlin's other binary bitwise operators |
<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,727: | Line 3,664: | ||
x ROR y = -2147483646 |
x ROR y = -2147483646 |
||
</pre> |
</pre> |
||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
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) |
<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,760: | Line 3,696: | ||
Example usage: |
Example usage: |
||
<syntaxhighlight lang=lisp> |
<syntaxhighlight lang="lisp"> |
||
> (bitwise 255 170) |
> (bitwise 255 170) |
||
170 |
170 |
||
Line 3,779: | Line 3,715: | ||
> |
> |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
Written as functions. |
Written as functions. |
||
<syntaxhighlight lang=lb> |
<syntaxhighlight lang="lb"> |
||
' bitwise operations on byte-sized variables |
' bitwise operations on byte-sized variables |
||
Line 3,830: | Line 3,765: | ||
end function |
end function |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{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) |
<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)</syntaxhighlight> |
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= |
<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,849: | Line 3,782: | ||
and: 2, or: 255, xor: 253, not: 4294967040</syntaxhighlight> |
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' |
<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,911: | Line 3,843: | ||
;Declare external fuctions |
;Declare external fuctions |
||
declare i32 @printf(i8* nocapture, ...) nounwind</syntaxhighlight> |
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 |
<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,926: | Line 3,857: | ||
bitwise 255 5</syntaxhighlight> |
bitwise 255 5</syntaxhighlight> |
||
The output of this program is: |
The output of this program is: |
||
<syntaxhighlight lang=logo>a and b: 5 |
<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,933: | Line 3,864: | ||
a lshift -b: 7 |
a lshift -b: 7 |
||
-a ashift -b: -8</syntaxhighlight> |
-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 |
<syntaxhighlight lang="lse64">over : 2 pick |
||
2dup : over over |
2dup : over over |
||
Line 3,947: | Line 3,877: | ||
\ a \ 7 bitwise # hex literals</syntaxhighlight> |
\ a \ 7 bitwise # hex literals</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
LuaBitOp implements bitwise functionality for Lua: |
LuaBitOp implements bitwise functionality for Lua: |
||
<syntaxhighlight lang=lua>local bit = require"bit" |
<syntaxhighlight lang="lua">local bit = require"bit" |
||
local vb = { |
local vb = { |
||
Line 4,025: | Line 3,954: | ||
==={{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 |
<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,050: | Line 3,979: | ||
AA55AA55 rol 4 = A55AA55A |
AA55AA55 rol 4 = A55AA55A |
||
AA55AA55 ror 4 = 5AA55AA5</pre> |
AA55AA55 ror 4 = 5AA55AA5</pre> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="maple"> |
||
with(Bits): |
with(Bits): |
||
bit:=proc(A,B) |
bit:=proc(A,B) |
||
Line 4,072: | Line 4,000: | ||
end proc; |
end proc; |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{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= |
<syntaxhighlight lang="mathematica">(*and xor and or*) |
||
BitAnd[integer1, integer2] |
BitAnd[integer1, integer2] |
||
BitXor[integer1, integer2] |
BitXor[integer1, integer2] |
||
Line 4,094: | Line 4,021: | ||
FromDigits[Prepend[Most[#], #[[1]]], 2] &[IntegerDigits[integer1, 2]]</syntaxhighlight> |
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= |
<syntaxhighlight lang="mathematica">BitXor[3333, 5555, 7777, 9999]</syntaxhighlight> |
||
gives back: |
gives back: |
||
<syntaxhighlight 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= |
<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,112: | Line 4,038: | ||
Output: |
Output: |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="matlab">>> bitwiseOps(255,2) |
||
255 and 2 = 2 |
255 and 2 = 2 |
||
255 or 2 = 255 |
255 or 2 = 255 |
||
Line 4,118: | Line 4,044: | ||
255 << 2 = 1020 |
255 << 2 = 1020 |
||
255 >> 2 = 63</syntaxhighlight> |
255 >> 2 = 63</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
<syntaxhighlight lang=maxima>load(functs)$ |
<syntaxhighlight lang="maxima">load(functs)$ |
||
a: 3661$ |
a: 3661$ |
||
Line 4,143: | Line 4,068: | ||
logand(a, -a - 1); |
logand(a, -a - 1); |
||
/* 0 */</syntaxhighlight> |
/* 0 */</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
<syntaxhighlight lang=maxscript>fn bitwise a b = |
<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,158: | Line 4,082: | ||
MAXScript doesn't have arithmetic shift or rotate operations. |
MAXScript doesn't have arithmetic shift or rotate operations. |
||
=={{header|ML/I}}== |
=={{header|ML/I}}== |
||
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= |
<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,178: | Line 4,101: | ||
*MCSET S10=2 |
*MCSET S10=2 |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
<syntaxhighlight lang=modula3>MODULE Bitwise EXPORTS Main; |
<syntaxhighlight lang="modula3">MODULE Bitwise EXPORTS Main; |
||
IMPORT IO, Fmt, Word; |
IMPORT IO, Fmt, Word; |
||
Line 4,215: | Line 4,137: | ||
c RightRotate b: f8000007 |
c RightRotate b: f8000007 |
||
</pre> |
</pre> |
||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="actionscript">/** |
||
<doc> |
<doc> |
||
<h2>bitwise operations</h2> |
<h2>bitwise operations</h2> |
||
Line 4,299: | Line 4,220: | ||
a ROL b: is not directly supported in Neko syntax |
a ROL b: is not directly supported in Neko syntax |
||
a ROR b: is not directly supported in Neko syntax</pre> |
a ROR b: is not directly supported in Neko syntax</pre> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="nemerle">def i = 255; |
||
def j = 2; |
def j = 2; |
||
Line 4,314: | Line 4,234: | ||
// 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</syntaxhighlight> |
// 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) = |
<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,323: | Line 4,242: | ||
echo "a << b: ", a shl b |
echo "a << b: ", a shl b |
||
echo "a >> b: ", a shr b</syntaxhighlight> |
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 |
<syntaxhighlight lang="nsis">Function Bitwise |
||
Push $0 |
Push $0 |
||
Push $1 |
Push $1 |
||
Line 4,353: | Line 4,271: | ||
Pop $0 |
Pop $0 |
||
FunctionEnd</syntaxhighlight> |
FunctionEnd</syntaxhighlight> |
||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
{{Works with|oo2c version 2}} |
{{Works with|oo2c version 2}} |
||
<syntaxhighlight lang=oberon2> |
<syntaxhighlight lang="oberon2"> |
||
MODULE Bitwise; |
MODULE Bitwise; |
||
IMPORT |
IMPORT |
||
Line 4,398: | Line 4,315: | ||
a arithmetic right shift b :> 2 |
a arithmetic right shift b :> 2 |
||
</pre> |
</pre> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
<syntaxhighlight lang=objeck>use IO; |
<syntaxhighlight lang="objeck">use IO; |
||
bundle Default { |
bundle Default { |
||
Line 4,417: | Line 4,333: | ||
} |
} |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
<syntaxhighlight lang=ocaml>let bitwise a b = |
<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,428: | Line 4,343: | ||
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> |
;;</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
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) |
<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,444: | Line 4,358: | ||
bitops(0x1e, 0x3);</syntaxhighlight> |
bitops(0x1e, 0x3);</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
There is no built-in for not and rotation |
There is no built-in for not and rotation |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="oforth">: bitwise(a, b) |
||
a b bitAnd println |
a b bitAnd println |
||
a b bitOr println |
a b bitOr println |
||
Line 4,455: | Line 4,368: | ||
a bitLeft(b) println |
a bitLeft(b) println |
||
a bitRight(b) println ;</syntaxhighlight> |
a bitRight(b) println ;</syntaxhighlight> |
||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
<syntaxhighlight lang= |
<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,487: | Line 4,399: | ||
a~bitor(b,p):001100110011010111111111 3335FF |
a~bitor(b,p):001100110011010111111111 3335FF |
||
</pre> |
</pre> |
||
=={{header|OpenEdge/Progress}}== |
=={{header|OpenEdge/Progress}}== |
||
The only bit operators available in OpenEdge are the GET-BITS() and PUT-BITS() functions. These functions can be used to implement all bitwise operators. |
The only bit operators available in OpenEdge are the GET-BITS() and PUT-BITS() functions. These functions can be used to implement all bitwise operators. |
||
=={{header|PARI/GP}}== |
=={{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)={ |
<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,502: | Line 4,412: | ||
print("Right shift: ",a>>b); |
print("Right shift: ",a>>b); |
||
}</syntaxhighlight> |
}</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 |
<syntaxhighlight lang="pascal">var |
||
a, b: integer; |
a, b: integer; |
||
begin |
begin |
||
Line 4,514: | Line 4,423: | ||
writeln('a xor b = ', a xor b) { 6 = 0110 } |
writeln('a xor b = ', a xor b) { 6 = 0110 } |
||
end.</syntaxhighlight> |
end.</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
<syntaxhighlight lang=perl>use integer; |
<syntaxhighlight lang="perl">use integer; |
||
sub bitwise($$) { |
sub bitwise($$) { |
||
Line 4,531: | Line 4,439: | ||
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift |
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift |
||
}</syntaxhighlight> |
}</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= |
<!--<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,586: | Line 4,493: | ||
ror(10000000000000000000000011111110,111) = 11111101000000000000000000000001 |
ror(10000000000000000000000011111110,111) = 11111101000000000000000000000001 |
||
</pre> |
</pre> |
||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="phixmonti">6 var a 3 var b |
||
def tab |
def tab |
||
Line 4,605: | Line 4,511: | ||
"XOR = " print tab a b bitxor printBits |
"XOR = " print tab a b bitxor printBits |
||
"NOT = " print tab a bitnot printBits</syntaxhighlight> |
"NOT = " print tab a bitnot printBits</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
<syntaxhighlight lang=php>function bitwise($a, $b) |
<syntaxhighlight lang="php">function bitwise($a, $b) |
||
{ |
{ |
||
function zerofill($a,$b) { |
function zerofill($a,$b) { |
||
Line 4,622: | Line 4,527: | ||
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift |
echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
PicoLisp has no specific word size. Numbers grow to arbitrary length. Therefore, |
PicoLisp has no specific word size. Numbers grow to arbitrary length. Therefore, |
||
Line 4,629: | Line 4,533: | ||
Bitwise AND: |
Bitwise AND: |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="picolisp">: (& 6 3) |
||
-> 2 |
-> 2 |
||
Line 4,636: | Line 4,540: | ||
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= |
<syntaxhighlight lang="picolisp">: (bit? 1 2) |
||
-> NIL |
-> NIL |
||
Line 4,645: | Line 4,549: | ||
-> 6</syntaxhighlight> |
-> 6</syntaxhighlight> |
||
Bitwise OR: |
Bitwise OR: |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="picolisp">: (| 1 2) |
||
-> 3 |
-> 3 |
||
Line 4,651: | Line 4,555: | ||
-> 15</syntaxhighlight> |
-> 15</syntaxhighlight> |
||
Bitwise XOR: |
Bitwise XOR: |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="picolisp">: (x| 2 7) |
||
-> 5 |
-> 5 |
||
Line 4,657: | Line 4,561: | ||
-> 4</syntaxhighlight> |
-> 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= |
<syntaxhighlight lang="picolisp">: (>> 1 8) |
||
-> 4 |
-> 4 |
||
Line 4,668: | Line 4,572: | ||
: (>> -1 -16) |
: (>> -1 -16) |
||
-> -32</syntaxhighlight> |
-> -32</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
Rotate operations are not available |
Rotate operations are not available |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="pike"> |
||
void bitwise(int a, int b) |
void bitwise(int a, int b) |
||
{ |
{ |
||
Line 4,701: | Line 4,604: | ||
a << b & 0xffffffff (32bit cap): 0xc0000000 |
a << b & 0xffffffff (32bit cap): 0xc0000000 |
||
</pre> |
</pre> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang=pli>/* PL/I can perform bit operations on binary integers. */ |
<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,729: | Line 4,631: | ||
u = substr(s, 2) || substr(s, 1, 1); /* implements rotate left. */ |
u = substr(s, 2) || substr(s, 1, 1); /* implements rotate left. */ |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
<syntaxhighlight lang=pop11>define bitwise(a, b); |
<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,744: | Line 4,645: | ||
Similarly, on infinitely precise numbers rotation is undefined. |
Similarly, on infinitely precise numbers rotation is undefined. |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
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= |
<syntaxhighlight lang="powershell">$X -band $Y |
||
$X -bor $Y |
$X -bor $Y |
||
$X -bxor $Y |
$X -bxor $Y |
||
Line 4,754: | Line 4,654: | ||
{{works with|PowerShell|3.0}} |
{{works with|PowerShell|3.0}} |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="powershell">$X -shl $Y |
||
# Arithmetic right shift |
# Arithmetic right shift |
||
$X -shr $Y |
$X -shr $Y |
||
Line 4,760: | Line 4,660: | ||
# 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))</syntaxhighlight> |
[System.Security.Cryptography.SHA256Managed].GetMethod('RotateRight', 'NonPublic, Static', $null, @([UInt32], [Int32]), $null).Invoke($null, @([uint32]$X, $Y))</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
<syntaxhighlight lang= |
<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,791: | Line 4,690: | ||
Debug Temp |
Debug Temp |
||
EndProcedure</syntaxhighlight> |
EndProcedure</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Python 3=== |
===Python 3=== |
||
Line 4,800: | Line 4,698: | ||
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): |
<syntaxhighlight lang="python">def bitwise_built_ins(width, a, b): |
||
mask = (1 << width) - 1 |
mask = (1 << width) - 1 |
||
print(f"""\ |
print(f"""\ |
||
Line 4,966: | Line 4,864: | ||
===Python 2=== |
===Python 2=== |
||
<syntaxhighlight lang=python>def bitwise(a, b): |
<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,978: | Line 4,876: | ||
Note: Newer Python versions (circa 2.4?) will automatically promote integers into "long integers" (arbitrary length, bounded by available memory). This can be noticed especially when using left shift operations. When using bitwise operations one usually wants to keep these bounded to specific sizes such as 8, 16, 32 or 64 bit widths. To do these we use the AND operator with specific values (bitmasks). For example: |
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: |
<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,989: | Line 4,887: | ||
We can easily implement our own rotation functions. For left rotations this is down by ORing the left shifted and masked lower bits against the right shifted upper bits. For right rotations we perform the converse operations, ORing a set of right shifted lower bits against the appropriate number of left shifted upper bits. |
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): |
<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,032: | Line 4,930: | ||
In this example we show a relatively straightforward function for converting integers into strings of bits, and another simple ''mask()'' function to create arbitrary lengths of bits against which we perform our masking operations. Also note that the implementation of these functions defaults to single bit rotations of 8-bit bytes. Additional arguments can be used to over-ride these defaults. Any case where the number of rotations modulo the width is zero represents a rotation of all bits back to their starting positions. This implementation should handle any integer number of rotations over bitfields of any valid (positive integer) length. |
In this example we show a relatively straightforward function for converting integers into strings of bits, and another simple ''mask()'' function to create arbitrary lengths of bits against which we perform our masking operations. Also note that the implementation of these functions defaults to single bit rotations of 8-bit bytes. Additional arguments can be used to over-ride these defaults. Any case where the number of rotations modulo the width is zero represents a rotation of all bits back to their starting positions. This implementation should handle any integer number of rotations over bitfields of any valid (positive integer) length. |
||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
<syntaxhighlight lang= |
<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,068: | Line 4,964: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Integers in Quackery are bignums, so the bitwise left rotate word <code>rot64</code> rotates specifically the least significant 64 bits of an integer. There is no corresponding bitwise right rotate, but it is readily defined from <code>rot64</code>. |
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= |
<syntaxhighlight lang="quackery"> [ [] swap |
||
64 times |
64 times |
||
[ 2 /mod |
[ 2 /mod |
||
Line 5,108: | Line 5,003: | ||
bitwise RROTATE: 1111111111111110000000000000000000000000000000000000000000011111 |
bitwise RROTATE: 1111111111111110000000000000000000000000000000000000000000011111 |
||
</pre> |
</pre> |
||
=={{header|R}}== |
=={{header|R}}== |
||
=== 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 |
<syntaxhighlight lang="rsplus"># Since R 3.0.0, the base package provides bitwise operators, see ?bitwAnd |
||
a <- 35 |
a <- 35 |
||
Line 5,126: | Line 5,020: | ||
===Using ''as.hexmode'' or ''as.octmode''=== |
===Using ''as.hexmode'' or ''as.octmode''=== |
||
<syntaxhighlight lang=rsplus>a <- as.hexmode(35) |
<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 |
||
Line 5,134: | Line 5,028: | ||
===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)) |
<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,149: | Line 5,043: | ||
===Using ''bitops'' package=== |
===Using ''bitops'' package=== |
||
<syntaxhighlight lang=rsplus>library(bitops) |
<syntaxhighlight lang="rsplus">library(bitops) |
||
bitAnd(35, 42) # 34 |
bitAnd(35, 42) # 34 |
||
bitOr(35, 42) # 43 |
bitOr(35, 42) # 43 |
||
Line 5,157: | Line 5,051: | ||
bitShiftR(35, 1) # 17 |
bitShiftR(35, 1) # 17 |
||
# Note that no bit rotation is provided in this package</syntaxhighlight> |
# Note that no bit rotation is provided in this package</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang=racket> |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(define a 255) |
(define a 255) |
||
Line 5,174: | Line 5,067: | ||
'(5 255 250 -256 8160 7) |
'(5 255 250 -256 8160 7) |
||
</pre> |
</pre> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
{{works with|Rakudo|2017.05}} |
{{works with|Rakudo|2017.05}} |
||
<syntaxhighlight lang=raku line>constant MAXINT = uint.Range.max; |
<syntaxhighlight lang="raku" line>constant MAXINT = uint.Range.max; |
||
constant BITS = MAXINT.base(2).chars; |
constant BITS = MAXINT.base(2).chars; |
||
Line 5,230: | Line 5,122: | ||
-65432 shift left 31: 1111111111111111100000000011010000000000000000000000000000000000 |
-65432 shift left 31: 1111111111111111100000000011010000000000000000000000000000000000 |
||
-65432 rotate left 31: 1111111111111111100000000011010001111111111111111111111111111111</pre> |
-65432 rotate left 31: 1111111111111111100000000011010001111111111111111111111111111111</pre> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
<syntaxhighlight lang=red>Red [Source: https://github.com/vazub/rosetta-red] |
<syntaxhighlight lang="red">Red [Source: https://github.com/vazub/rosetta-red] |
||
a: 10 |
a: 10 |
||
Line 5,262: | Line 5,153: | ||
a << b: 40 |
a << b: 40 |
||
</pre> |
</pre> |
||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
There is no predefined arithmetic shifts in Retro. |
There is no predefined arithmetic shifts in Retro. |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="retro"> |
||
: bitwise ( ab- ) |
: bitwise ( ab- ) |
||
cr |
cr |
||
Line 5,278: | Line 5,168: | ||
2over >> "a >> b = %d\n" puts |
2over >> "a >> b = %d\n" puts |
||
2drop ;</syntaxhighlight> |
2drop ;</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
<pre> |
<pre> |
||
Line 5,290: | Line 5,179: | ||
╚═══════════════════════════════════════════════════════════════════════════════════════╝ |
╚═══════════════════════════════════════════════════════════════════════════════════════╝ |
||
</pre> |
</pre> |
||
<syntaxhighlight lang=rexx>/*REXX program performs bit─wise operations on integers: & | && ¬ «L »R */ |
<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,326: | Line 5,215: | ||
2 A [»B] 10 |
2 A [»B] 10 |
||
</pre> |
</pre> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
<syntaxhighlight lang=ring> |
<syntaxhighlight lang="ring"> |
||
x = 8 |
x = 8 |
||
y = 2 |
y = 2 |
||
Line 5,339: | Line 5,227: | ||
see "x >> y - Binary Right Shift : " + (x >> y) + nl |
see "x >> y - Binary Right Shift : " + (x >> y) + nl |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
Line 5,345: | Line 5,232: | ||
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= |
<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,358: | Line 5,245: | ||
>> 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</syntaxhighlight> |
0x00000001</syntaxhighlight> |
||
=={{header|Robotic}}== |
=={{header|Robotic}}== |
||
<syntaxhighlight lang=robotic> |
<syntaxhighlight lang="robotic"> |
||
input string "First value" |
input string "First value" |
||
set "local1" to "input" |
set "local1" to "input" |
||
Line 5,377: | Line 5,263: | ||
. "Bitwise rotation is not natively supported" |
. "Bitwise rotation is not natively supported" |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
<syntaxhighlight lang=ruby>def bitwise(a, b) |
<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,404: | Line 5,289: | ||
a >> b : 1 0000000000000001 |
a >> b : 1 0000000000000001 |
||
</pre> |
</pre> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
<syntaxhighlight lang=rust>fn main() { |
<syntaxhighlight lang="rust">fn main() { |
||
let a: u8 = 105; |
let a: u8 = 105; |
||
let b: u8 = 91; |
let b: u8 = 91; |
||
Line 5,431: | Line 5,315: | ||
a >> 3 = 00001101 |
a >> 3 = 00001101 |
||
</pre> |
</pre> |
||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
<syntaxhighlight lang=sas>/* rotations are not available, but are easy to implement with the other bitwise operators */ |
<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,445: | Line 5,328: | ||
put _all_; |
put _all_; |
||
run;</syntaxhighlight> |
run;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
<syntaxhighlight lang=scala>def bitwise(a: Int, b: Int) { |
<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,459: | Line 5,341: | ||
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right |
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right |
||
}</syntaxhighlight> |
}</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))) |
<syntaxhighlight lang="scheme">(import (rnrs arithmetic bitwise (6))) |
||
(define (bitwise a b) |
(define (bitwise a b) |
||
Line 5,478: | Line 5,359: | ||
(bitwise 255 5)</syntaxhighlight> |
(bitwise 255 5)</syntaxhighlight> |
||
Output: |
Output: |
||
<syntaxhighlight lang=text>5 |
<syntaxhighlight lang="text">5 |
||
255 |
255 |
||
250 |
250 |
||
Line 5,485: | Line 5,366: | ||
''Note: bitwise operations were also described in [http://srfi.schemers.org/srfi-60/ SRFI-60], with additional aliases (and previously discussed in [http://srfi.schemers.org/srfi-33/ SRFI-33] which remained draft).'' |
''Note: bitwise operations were also described in [http://srfi.schemers.org/srfi-60/ SRFI-60], with additional aliases (and previously discussed in [http://srfi.schemers.org/srfi-33/ SRFI-33] which remained draft).'' |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
The type [http://seed7.sourceforge.net/manual/types.htm#integer integer] is intended for arithmetic operations. |
The type [http://seed7.sourceforge.net/manual/types.htm#integer integer] is intended for arithmetic operations. |
||
Line 5,494: | Line 5,374: | ||
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"; |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "bin32.s7i"; |
include "bin32.s7i"; |
||
Line 5,542: | Line 5,422: | ||
a rolR b: 11010000000000000000001111111000 |
a rolR b: 11010000000000000000001111111000 |
||
</pre> |
</pre> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
<syntaxhighlight lang=ruby>func bitwise(a, b) { |
<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,563: | Line 5,442: | ||
a >> b : 1 |
a >> b : 1 |
||
</pre> |
</pre> |
||
=={{header|Simula}}== |
=={{header|Simula}}== |
||
<syntaxhighlight lang=simula>BEGIN |
<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,678: | Line 5,556: | ||
A ROTR B : -1073741823 |
A ROTR B : -1073741823 |
||
</pre> |
</pre> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
<syntaxhighlight lang=slate>[ |:a :b | |
<syntaxhighlight lang="slate">[ |:a :b | |
||
inform: (a bitAnd: b) printString. |
inform: (a bitAnd: b) printString. |
||
Line 5,691: | Line 5,568: | ||
] applyTo: {8. 12}.</syntaxhighlight> |
] applyTo: {8. 12}.</syntaxhighlight> |
||
'''Bold text''' |
'''Bold text''' |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{works with|GNU Smalltalk}} |
{{works with|GNU Smalltalk}} |
||
Line 5,697: | Line 5,573: | ||
{{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 | |
<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,710: | Line 5,586: | ||
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" |
<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,720: | Line 5,596: | ||
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). |
||
=={{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) = ( |
<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,732: | Line 5,607: | ||
)</syntaxhighlight> |
)</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) = ( |
<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,741: | Line 5,616: | ||
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> |
)</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
Stata does not have bitwise operators as of version 15.1. It's possible to use Mata functions '''[https://www.stata.com/help.cgi?mf_inbase inbase]''' and '''frombase''' to convert integers to binary strings, and operate on these, but it will be much slower than native operators. William Matsuoka has written functions for this [http://www.wmatsuoka.com/stata/building-an-api-library here]. |
Stata does not have bitwise operators as of version 15.1. It's possible to use Mata functions '''[https://www.stata.com/help.cgi?mf_inbase inbase]''' and '''frombase''' to convert integers to binary strings, and operate on these, but it will be much slower than native operators. William Matsuoka has written functions for this [http://www.wmatsuoka.com/stata/building-an-api-library here]. |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
<syntaxhighlight lang=swift>func bitwise(a: Int, b: Int) { |
<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,771: | Line 5,644: | ||
a lsr b: 2305843009213693950 |
a lsr b: 2305843009213693950 |
||
</pre> |
</pre> |
||
=={{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= |
<syntaxhighlight lang="systemverilog">program main; |
||
initial begin |
initial begin |
||
Line 5,797: | Line 5,669: | ||
If we want to do a variable bit rotation, then we need to think in hardware terms, and build a mux structure (this could be a function, but using a module allows it to be parameterized: |
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= |
<syntaxhighlight lang="systemverilog">module rotate(in, out, shift); |
||
parameter BITS = 32; |
parameter BITS = 32; |
||
Line 5,811: | Line 5,683: | ||
of course, one could always write the foreach loop inline. |
of course, one could always write the foreach loop inline. |
||
=={{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> |
<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,840: | Line 5,711: | ||
f075 rotated right 3 bits is be0e |
f075 rotated right 3 bits is be0e |
||
</pre> |
</pre> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
<syntaxhighlight lang=tcl>proc bitwise {a b} { |
<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,851: | Line 5,721: | ||
}</syntaxhighlight> |
}</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} { |
<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,864: | Line 5,734: | ||
}]] |
}]] |
||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
Line 5,871: | Line 5,740: | ||
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) |
<syntaxhighlight lang="ti89b">bitwise(a,b) |
||
Prgm |
Prgm |
||
Local show, oldbase |
Local show, oldbase |
||
Line 5,894: | Line 5,763: | ||
setMode("Base",oldbase) |
setMode("Base",oldbase) |
||
EndPrgm</syntaxhighlight> |
EndPrgm</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
<syntaxhighlight lang= |
<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,922: | Line 5,790: | ||
NOT: ~255 = -256 |
NOT: ~255 = -256 |
||
</pre> |
</pre> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
In VBA, the logical operators And, Or, Xor, Not are actually binary operators. There are also Eqv and Imp (for bitwise "equivalence" and "logical implication"). |
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 |
<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,936: | Line 5,803: | ||
The other operations in the task are not builtin, but are easy to implement. Integers are signed, and overflow throws and exception, one must take care of this. |
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 |
<syntaxhighlight lang="vb">Function MaskL(k As Integer) As Long |
||
If k < 1 Then |
If k < 1 Then |
||
MaskL = 0 |
MaskL = 0 |
||
Line 6,018: | Line 5,885: | ||
Examples |
Examples |
||
<syntaxhighlight lang=vb>Debug.Print Hex(MaskL(8)) 'FF000000 |
<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,030: | Line 5,897: | ||
Debug.Print Hex(RotateR(65535, -8)) 'FFFF00 |
Debug.Print Hex(RotateR(65535, -8)) 'FFFF00 |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
=={{header|Visual Basic}}== |
=={{header|Visual Basic}}== |
||
{{works with|Visual Basic|VB6 Standard}} |
{{works with|Visual Basic|VB6 Standard}} |
||
identical syntax as in [[#VBA]]. |
identical syntax as in [[#VBA]]. |
||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
<syntaxhighlight lang=vbnet>Sub Test(a as Integer, b as Integer) |
<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,046: | Line 5,911: | ||
Visual Basic doesn't have built-in support for bitwise rotation. |
Visual Basic doesn't have built-in support for bitwise rotation. |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
In Wren all numbers are represented in 64-bit floating point form. |
In Wren all numbers are represented in 64-bit floating point form. |
||
Line 6,055: | Line 5,919: | ||
Given this limitation, there is no difference between logical and arithmetic left and right shift operations. Although Wren doesn't support circular shift operators, it is not difficult to write functions to perform them. |
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) } |
<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,090: | Line 5,954: | ||
x rr y = 2147483650 |
x rr y = 2147483650 |
||
</pre> |
</pre> |
||
=={{header|x86 Assembly}}== |
=={{header|x86 Assembly}}== |
||
{{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 |
<syntaxhighlight lang="asm"> extern printf |
||
global main |
global main |
||
Line 6,198: | Line 6,061: | ||
end</syntaxhighlight> |
end</syntaxhighlight> |
||
=={{header|XBasic}}== |
=={{header|XBasic}}== |
||
{{works with|Windows XBasic}} |
{{works with|Windows XBasic}} |
||
<syntaxhighlight lang=xbasic> |
<syntaxhighlight lang="xbasic"> |
||
PROGRAM "bitwise" |
PROGRAM "bitwise" |
||
Line 6,268: | Line 6,130: | ||
10101 Rotr 11: 10100000000000000000000000000010 |
10101 Rotr 11: 10100000000000000000000000000010 |
||
</pre> |
</pre> |
||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
<syntaxhighlight lang=lisp>(defun bitwise-operations (a b) |
<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,278: | Line 6,139: | ||
(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)))) )</syntaxhighlight> |
(print `(,a arithmetic right shift by ,b = ,(ash a (- b)))) )</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
<syntaxhighlight lang= |
<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,296: | Line 6,156: | ||
operator was introduced at a time when only uppercase characters were |
operator was introduced at a time when only uppercase characters were |
||
available (such as on the Apple II). The XOR operator was added later. |
available (such as on the Apple II). The XOR operator was added later. |
||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="yabasic">sub formBin$(n) |
||
return right$("00000000" + bin$(n), 8) |
return right$("00000000" + bin$(n), 8) |
||
end sub |
end sub |
||
Line 6,317: | Line 6,176: | ||
XOR = 00000101 |
XOR = 00000101 |
||
NOT 6 = 11111001</pre> |
NOT 6 = 11111001</pre> |
||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |
||
;AND |
;AND |
||
<syntaxhighlight lang=z80>LD A,&05 |
<syntaxhighlight lang="z80">LD A,&05 |
||
AND &1F ;0x05 & 0x1F</syntaxhighlight> |
AND &1F ;0x05 & 0x1F</syntaxhighlight> |
||
;OR |
;OR |
||
<syntaxhighlight lang=z80>LD A,&05 |
<syntaxhighlight lang="z80">LD A,&05 |
||
OR &1F ;0x05 | 0x1F</syntaxhighlight> |
OR &1F ;0x05 | 0x1F</syntaxhighlight> |
||
;XOR |
;XOR |
||
<syntaxhighlight lang=z80>LD A,&05 |
<syntaxhighlight lang="z80">LD A,&05 |
||
XOR &1F ;0x05 ^ 0x1F</syntaxhighlight> |
XOR &1F ;0x05 ^ 0x1F</syntaxhighlight> |
||
;NOT |
;NOT |
||
<syntaxhighlight lang=z80>LD A,&05 |
<syntaxhighlight lang="z80">LD A,&05 |
||
CPL</syntaxhighlight> |
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 |
<syntaxhighlight lang="z80">LD A,&05 |
||
SLA A</syntaxhighlight> |
SLA A</syntaxhighlight> |
||
;Right Shift |
;Right Shift |
||
<syntaxhighlight lang=z80>LD A,&05 |
<syntaxhighlight lang="z80">LD A,&05 |
||
SRL A</syntaxhighlight> |
SRL A</syntaxhighlight> |
||
;Arithmetic Right Shift |
;Arithmetic Right Shift |
||
<syntaxhighlight lang=z80>LD A,&05 |
<syntaxhighlight lang="z80">LD A,&05 |
||
SRA A</syntaxhighlight> |
SRA A</syntaxhighlight> |
||
Line 6,351: | Line 6,209: | ||
* <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 |
<syntaxhighlight lang="z80">LD A,&05 |
||
RLA |
RLA |
||
Line 6,362: | Line 6,220: | ||
LD A,&05 |
LD A,&05 |
||
RRCA</syntaxhighlight> |
RRCA</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
No bitwise rotates. Shifts are unsigned. |
No bitwise rotates. Shifts are unsigned. |
||
<syntaxhighlight lang=zkl>(7).bitAnd(1) //-->1 |
<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,375: | Line 6,230: | ||
(-1).toString(16) //-->ffffffffffffffff |
(-1).toString(16) //-->ffffffffffffffff |
||
(-1).shiftRight(1).toString(16) //-->7fffffffffffffff</syntaxhighlight> |
(-1).shiftRight(1).toString(16) //-->7fffffffffffffff</syntaxhighlight> |
||
{{omit from|bc|No built-in bitwise operations}} |
{{omit from|bc|No built-in bitwise operations}} |
||
{{omit from|dc|No built-in bitwise operations}} |
{{omit from|dc|No built-in bitwise operations}} |