Bitwise operations: Difference between revisions

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

edits