Bitwise operations: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|Phix}}: replaced (inline assembly version) with a js-compatible version) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 12:
=={{header|11l}}==
{{trans|Kotlin}}
<
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))</
{{out}}
<pre>
Line 39:
=={{header|360 Assembly}}==
<
BITWISE CSECT
USING BITWISE,R13
Line 120:
PG DS CL12
YREGS
END BITWISE</
{{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 #.)
<
STA temp ;temp equals 5 for the following</
;AND
<
AND temp</
;OR
<
ORA temp</
;XOR
<
EOR temp</
;NOT
<
EOR #255</
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.
<
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</
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.)
<
ROL ;if the carry was set prior to the ROL, A = 3. If the carry was clear, A = 2.</
<
ROR ;if the carry was set prior to the ROR, A = 0x80. If clear, A = 0.</
=={{header|68000 Assembly}}==
Like with most 68000 commands, you can specify a length parameter. Anything outside that length is unaffected by the operation.
;AND
<
MOVE.W #$200,D1
AND.W D0,D1</
;OR
<
MOVE.W #$200,D1
OR.W D0,D1</
;XOR
<
MOVE.W #$200,D1
EOR.W D0,D1</
;NOT
<
NOT.W D0</
;Left Shift
<
MOVE.W #$04,D1
LSL.W D1,D0 ;shifts 0x00FF left 4 bits</
;Right Shift
<
MOVE.W #$04,D1
LSR.W D1,D0 ;shifts 0x00FF right 4 bits</
;Arithmetic Right Shift
<
MOVE.W #$04,D1
ASR.W D1,D0 ;shifts 0xFF00 right 4 bits, preserving its sign</
;Left Rotate
<
MOVE.W #$04,D1
ROL.W D1,D0</
;Right Rotate
<
MOVE.W #$04,D1
ROR.W D1,D0</
;Left Rotate Through Extend Flag
<
MOVE.W #$04,D1
ROXL.W D1,D0</
;Right Rotate Through Extend Flag
<
MOVE.W #$04,D1
ROXR.W D1,D0</
=={{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.
<
anl a, b
Line 285:
loop:
rr a
djnz b, loop</
=={{header|8086 Assembly}}==
;AND
<
MOV BX,0444h
AND AX,BX</
;OR
<
MOV BX,0444h
OR AX,BX</
;XOR
<
MOV BX,0444h
XOR AX,BX</
;NOT
<
NOT AX</
;Left Shift
<
MOV CL,02h
SHL AX,CL</
;Right Shift
<
MOV CL,02h
SHR AX,CL</
;Arithmetic Right Shift
<
MOV CL,02h
SAR AX,CL</
;Left Rotate
<
MOV CL,02h
ROL AX,CL</
;Right Rotate
<
MOV CL,02h
ROR AX,CL</
;Left Rotate Through Carry
<
MOV CL,02h
RCL AX,CL</
;Right Rotate Through Carry
<
MOV CL,02h
RCR AX,CL</
=={{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.
<
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>
{{output}}
Line 642:
=={{header|ACL2}}==
Unlisted operations are not available
<
(list (logand a b)
(logior a b)
Line 648:
(lognot a)
(ash a b)
(ash a (- b))))</
=={{header|Action!}}==
<
RETURN (a!$FF)
Line 674:
res=a LSH b
PrintF("%B SHL %B = %B%E",a,b,res)
RETURN</
{{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.
<
{
trace("And: ", a & b);
Line 697:
trace("Right Shift(Arithmetic): ", a >> b);
trace("Right Shift(Logical): ", a >>> b);
}</
=={{header|Ada}}==
The following program performs all required operations and prints the resulting values in base 2 for easy checking of the bit values.
<
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;</
=={{header|Aikido}}==
Line 730:
There is no rotate support built in to Aikido.
<
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
}</
=={{header|ALGOL 68}}==
Line 747:
* 2r00000000000000000000000010101010, 4r0000000000002222, 8r00000000252, 16r000000aa
* and as an array of BOOL: FFFFFFFFFFFFFFFFFFFFFFFFTFTFTFTF
<
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
)</
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:
<
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:]))</
Output:
<pre>
Line 856:
=={{header|ALGOL W}}==
<
% 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 ;</
=={{header|AppleScript}}==
Line 893:
<
use framework "Foundation"
use scripting additions
Line 1,247:
return lst
end tell
end zipWith</
{{Out}}
<pre>32 bit signed integers (in two's complement binary encoding)
Line 1,264:
'''Second option''' – writing our own bitwise functions for Applescript:
<
use framework "Foundation"
use scripting additions
Line 1,751:
return lst
end tell
end zipWith</
{{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.
<
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</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<
/* ARM assembly Raspberry PI */
Line 2,018:
</syntaxhighlight>
=={{header|Arturo}}==
<
b: 2
Line 2,029:
print ["NOT" a "=" not a]
print [a "SHL" b "=" shl a b]
print [a "SHR" b "=" shr a b]</
{{out}}
Line 2,041:
=={{header|AutoHotkey}}==
<
bitwise(a, b)
{
Line 2,050:
MsgBox % "a << b: " . a << b ; left shift
MsgBox % "a >> b: " . a >> b ; arithmetic right shift
}</
=={{header|AutoIt}}==
No arithmetic shift.
<
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</
{{out}}
Line 2,083:
{{works with|gawk}}
<
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
}</
[[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}}==
<
r₁→A
r₂→B
Line 2,105:
Disp "NOT:",not(A)ʳ▶Dec,i
.No language support for shifts or rotations
Return</
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.
<
{{Out}}
Line 2,128:
The cnot operator works on just one operand:
<syntaxhighlight lang
{{Out}}
Line 2,136:
{{works with|QuickBasic|4.5}}
QuickBasic does not have shift or rotate operations defined. Here are the logical operations:
<
PRINT a AND b
PRINT a OR b
PRINT a XOR b
PRINT NOT a
END SUB</
{{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.
<
DIM u AS UInteger
Line 2,156:
u = a
PRINT "a SHR b (logical) = "; u SHR b
END SUB</
==={{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.
<
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</
{{in}}
<pre>A=? 2
Line 2,178:
==={{header|IS-BASIC}}===
<
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)</
==={{header|Sinclair ZX81 BASIC}}===
Line 2,193:
The disassembly of the Z80 code would be:
<
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</
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.
<
20 INPUT A
30 INPUT B
Line 2,232:
230 POKE 16514,USR 16516
240 NEXT I
250 PRINT A;" << ";B;" = ";PEEK 16514</
{{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.
<
REM VARIABLES
REM A = first number
Line 2,326:
IF P = 0 THEN RETURN
GOTO 500
</syntaxhighlight>
=={{header|BASIC256}}==
<
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</
=={{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.
<
@echo off
setlocal
Line 2,418:
)
exit /b
</syntaxhighlight>
Sample output
Line 2,465:
=={{header|BBC BASIC}}==
<
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</
=={{header|beeswax}}==
<
###>N{` AND `~{~` = `&{Nz1~3J
UXe#
Line 2,503:
###
>UX`-`!P{M!` >> `~{~` = `!)!`-`M!{` , interpreted as (negative) signed Int64 number (MSB=1)`NN;
#>e#</
Example:
<
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)</
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
<
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:
<
A ROR B = A>>>(B%64)+A<<(64-B%64)</
=={{header|Befunge}}==
<
1 2 3 4 5 6>61g-:| 8 9
>&&\481p >88*61p371p >:61g\`!:68*+71g81gp| 7 >61g2/61p71g1+71pv
Line 2,561:
^ < G
</syntaxhighlight>
The labelled points (1 to G) are:
1. Read in A and B,
Line 2,592:
=={{header|C}}==
<
{
printf("a and b: %d\n", a & b);
Line 2,605:
/* there are no rotation operators in C */
return 0;
}</
To rotate an integer, you can combine a left shift and a right shift:
<
unsigned int rotr(unsigned int x, unsigned int s)
{
return (x >> s) | (x << 32 - s);
}</
movl 4(%esp), %eax ; arg1: x
movl 8(%esp), %ecx ; arg2: s
rorl %cl, %eax ; right rotate x by s
ret</
=={{header|C sharp|C#}}==
<
{
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#
}</
=={{header|C++}}==
{{trans|C}}
<
void bitwise(int a, int b)
Line 2,658:
std::cout << "a ror b: " << std::rotr(ua, b) << '\n';
}</
=={{header|Clojure}}==
<
(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.</
=={{header|COBOL}}==
Results are displayed in decimal.
<
PROGRAM-ID. bitwise-ops.
Line 2,705:
GOBACK
.</
{{works with|Visual COBOL}}
<
PROGRAM-ID. mf-bitwise-ops.
Line 2,748:
GOBACK
.</
=={{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
<
f = (a, b) ->
p "and", a & b
Line 2,766:
f(10,2)
</syntaxhighlight>
output
<syntaxhighlight lang=text>
> coffee foo.coffee
and 2
Line 2,777:
<< 40
>> 2
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(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
)</
Left and right logical shift may be implemented by the following functions:
<
(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>
Left and right rotation may be implemented by the following functions:
<
(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>
=={{header|D}}==
<
return (x >>> shift) | (x << (T.sizeof * 8 - shift));
}
Line 2,845:
testBit(a, b);
}</
{{out}}
<pre>Input: a = 255, b = 2
Line 2,859:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 2,872:
// there are no built-in rotation operators in Delphi
Readln;
end.</
=={{header|DWScript}}==
<
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));</
=={{header|E}}==
E provides arbitrary-size integers, so there is no distinct arithmetic and logical shift right. E does not provide bit rotate operations.
<
println(`Bitwise operations:
a AND b: ${a & b}
Line 2,894:
a right shift b: ${a >> b}
`)
}</
=={{header|ECL}}==
<
BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION
BitAND := A & B;
Line 2,927:
*/
</syntaxhighlight>
=={{header|Elena}}==
ELENA 4.x :
<
extension testOp
Line 2,949:
{
console.loadLineTo(new Integer()).bitwiseTest(console.loadLineTo(new Integer()))
}</
{{out}}
<pre>
Line 2,961:
=={{header|Elixir}}==
<
use Bitwise
Line 2,982:
end
Bitwise_operation.test</
{{out}}
Line 3,006:
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate.
<
-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>
outputs:
<
255 band 170 = 170
255 bor 170 = 255
Line 3,030:
255 bsl 170 = 381627307539845370001346183518875822092557105621893120
255 bsr 170 = 0
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
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.</
=={{header|Factor}}==
<
{
[ bitand "a AND b: " write . ]
Line 3,052:
[ abs shift "a asl b: " write . ]
[ neg shift "a asr b: " write . ]
} 2cleave</
outputs:
<
b=5
a AND b: 5
Line 3,062:
NOT a: -256
a asl b: 8160
a asr b: 7</
Currently rotation and logical shifts are not implemented.
=={{header|FALSE}}==
Only AND, OR, and NOT are available.
<
\$@$@$@$@\ { 3 copies }
"a & b = "&."
a | b = "|."
~a = "%~."
"</
=={{header|Forth}}==
<
: bitwise ( a b -- )
cr ." a = " over . ." b = " dup .
Line 3,085:
cr ." a shr b = " 2dup rshift .
cr ." a ashr b = " 2dup arshift .
2drop ;</
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:
<
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)</
The following INTRINSIC ELEMENTAL SUBROUTINE is also defined:
<
<
program bits_rosetta
implicit none
Line 3,146:
end program bits_rosetta
</syntaxhighlight>
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>
=={{header|Free Pascal}}==
<
{$mode objfpc}
var
Line 3,178:
writeln('2 sar 3 = ', sarshortint(x,y));
Readln;
end.</
=={{header|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</
{{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.
<
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</
Output:
Line 3,315:
=={{header|Go}}==
<
import "fmt"
Line 3,352:
var a, b int16 = -460, 6
bitwise(a, b)
}</
Output:
<pre>a: 1111111000110100
Line 3,368:
=={{header|Groovy}}==
<
println """
a & b = ${a} & ${b} = ${a & b}
Line 3,378:
a >>> b = ${a} >>> ${b} = ${a >>> b} logical (zero-filling) shift
"""
}</
Program:
<syntaxhighlight lang
Output:
Line 3,395:
Harbour language has a set of core functions, which are fully optimized
at compile time, to perform bitwise operations.
<
PROCEDURE Main(...)
local n1 := 42, n2 := 2
Line 3,439:
return
</syntaxhighlight>
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.
<
bitwise :: Int -> Int -> IO ()
Line 3,481:
main :: IO ()
main = bitwise 255 170</
{{Out}}
<pre>170
Line 3,503:
=={{header|HicEst}}==
There is no rotate and no shift support built in to HicEst
<
i = IOR( k, j)
i = IEOR(k, j)
i = NOT( k )</
=={{header|HPPPL}}==
<
BEGIN
PRINT(BITAND(a, b));
Line 3,518:
PRINT(BITSR(a, b));
// HPPPL has no builtin rotates or arithmetic right shift.
END;</
=={{header|Icon}} and {{header|Unicon}}==
<
bitdemo(255,2)
bitdemo(-15,3)
Line 3,541:
procedure demowrite(vs,v)
return write(vs, ": ", v, " = ", int2bit(v),"b")
end</
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.
<
print "a and b: ", a & b, "^";
print "a or b: ", a | b, "^";
Line 3,584:
print "a >> b (logical): ", temp, "^";
];
</syntaxhighlight>
=={{header|J}}==
Line 3,590:
Here are the "[http://www.jsoftware.com/help/dictionary/dbdotn.htm bitwise operators]":
<
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.~ -</
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:
<
:
smoutput (((":x),"1' ',.(>u),.' '),"1":y),"1' => ',"1'.X'{~#:x u`:0 y
)</
And here they are in action:
<
254 bAND 3 => ............................X.
254 bOR 3 => ......................XXXXXXXX
Line 3,618:
254 bRAshift 3 => .........................XXXXX
254 bLrot 3 => ...................XXXXXXX....
254 bRrot 3 => .........................XXXXX</
Further test
<syntaxhighlight lang=j>
bXOR/ 3333 5555 7777 9999
8664
</syntaxhighlight>
=={{header|Java}}==
<
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+
}</
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:
<
a = a << 3;
a *= 8; //2 * 2 * 2 = 8
a = a * 8;</
=={{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.
<
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
}</
=={{header|Julia}}==
<
@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>
{{out}}
Line 3,691:
=={{header|Kotlin}}==
<
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}")
}</
{{out}}
Line 3,731:
All these operations are built-in functions except right arithmetic shift, left rotate, and right rotate.
<
(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>
Example usage:
<
> (bitwise 255 170)
170
Line 3,778:
ok
>
</syntaxhighlight>
=={{header|Liberty BASIC}}==
Written as functions.
<syntaxhighlight lang=lb>
' bitwise operations on byte-sized variables
Line 3,829:
dec2Bin$ =right$( "00000000" +dec2Bin$, 8)
end function
</syntaxhighlight>
=={{header|Lingo}}==
Lingo has built-in functions for bitwise AND, OR, XOR and NOT:
<
put bitOR(2,7)
put bitXOR(2,7)
put bitNOT(7)</
Bit shifting and rotating has to be implemented by custom functions.
=={{header|LiveCode}}==
<
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</
LiveCode does not provide built-in bit-shift operations.
=={{header|LLVM}}==
<
;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</
=={{header|Logo}}==
{{works with|UCB Logo}}
<
(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</
The output of this program is:
<
a or b: 255
a xor b: 250
Line 3,932:
a lshift b: 8160
a lshift -b: 7
-a ashift -b: -8</
=={{header|LSE64}}==
{{incorrect|LSE64|No reason given.}}
<
2dup : over over
Line 3,946:
" not A=" ,t ~ ,h nl
\ a \ 7 bitwise # hex literals</
=={{header|Lua}}==
Line 3,952:
LuaBitOp implements bitwise functionality for Lua:
<
local vb = {
Line 4,017:
assert(bit.bxor(1,2) == 3)
assert(bit.bor(1,2,4,8,16,32,64,128) == 255)
</syntaxhighlight>
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:
<
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)))</
{{out}}
<pre>AA55AA55 and 4 = 4
Line 4,052:
=={{header|Maple}}==
<
with(Bits):
bit:=proc(A,B)
Line 4,071:
return a,b,c,d,e,f,g,i;
end proc;
</syntaxhighlight>
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
Most functions are built-in or can be made really easily:
<
BitAnd[integer1, integer2]
BitXor[integer1, integer2]
Line 4,092:
(*right arithmetic shift*)
FromDigits[Prepend[Most[#], #[[1]]], 2] &[IntegerDigits[integer1, 2]]</
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:
<
gives back:
<syntaxhighlight lang
=={{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]
<
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</
Output:
<
255 and 2 = 2
255 or 2 = 255
255 xor 2 = 253
255 << 2 = 1020
255 >> 2 = 63</
=={{header|Maxima}}==
<
a: 3661$
Line 4,142:
logand(a, -a - 1);
/* 0 */</
=={{header|MAXScript}}==
<
(
format "a and b: %\n" (bit.and a b)
Line 4,155:
)
bitwise 255 170</
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.
<
"" Bitwise operations
"" assumes macros on input stream 1, terminal on stream 2
Line 4,177:
MCSET S1=1
*MCSET S10=2
</syntaxhighlight>
=={{header|Modula-3}}==
<
IMPORT IO, Fmt, Word;
Line 4,202:
BEGIN
Bitwise(255, 5);
END Bitwise.</
Output:
Line 4,217:
=={{header|Neko}}==
<
<doc>
<h2>bitwise operations</h2>
Line 4,273:
if b == null b = 0;
bitwise(a,b);</
{{out}}
Line 4,301:
=={{header|Nemerle}}==
<
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</
=={{header|Nim}}==
<
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</
=={{header|NSIS}}==
All bitwise operations in NSIS are handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 IntOp] instruction.
<
Push $0
Push $1
Line 4,352:
Pop $1
Pop $0
FunctionEnd</
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<
MODULE Bitwise;
IMPORT
Line 4,383:
Do(10,2);
END Bitwise.
</syntaxhighlight>
{{out}}
<pre>
Line 4,400:
=={{header|Objeck}}==
<
bundle Default {
Line 4,416:
}
}
}</
=={{header|OCaml}}==
<
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 *)
;;</
=={{header|Octave}}==
Line 4,433:
There's no arithmetic shift nor rotation (and the not can be done through a xor)
<
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);</
=={{header|Oforth}}==
Line 4,449:
There is no built-in for not and rotation
<
a b bitAnd println
a b bitOr println
a b bitXor println
a bitLeft(b) println
a bitRight(b) println ;</
=={{header|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)))</
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>.
<
print("And: "bitand(a,b));
print("Or: "bitor(a,b));
Line 4,501:
print("Left shift: ",a<<b);
print("Right shift: ",a>>b);
}</
=={{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:
<
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.</
=={{header|Perl}}==
<
sub bitwise($$) {
Line 4,530:
print 'a << b: ', $a << $b, "\n"; # left shift
print 'a >> b: ', $a >> $b, "\n"; # arithmetic right shift
}</
=={{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.
<!--<
<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>
<!--</
{{out}}
<pre>
Line 4,588:
=={{header|Phixmonti}}==
<
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</
=={{header|PHP}}==
<
{
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
}</
=={{header|PicoLisp}}==
Line 4,629:
Bitwise AND:
<
-> 2
: (& 7 3 1)
-> 1</
Bitwise AND-Test (tests if all bits in the first argument are set in the
following arguments):
<
-> NIL
Line 4,643:
: (bit? 6 15 255)
-> 6</
Bitwise OR:
<
-> 3
: (| 1 2 4 8)
-> 15</
Bitwise XOR:
<
-> 5
: (x| 2 7 1)
-> 4</
Shift (right with a positive count, left with a negative count):
<
-> 4
Line 4,667:
: (>> -1 -16)
-> -32</
=={{header|Pike}}==
Rotate operations are not available
<
void bitwise(int a, int b)
{
Line 4,690:
bitwise(255, 30);
}
</syntaxhighlight>
{{Out}}
<pre>
Line 4,703:
=={{header|PL/I}}==
<
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>
=={{header|Pop11}}==
<
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;</
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}}
<
$X -bor $Y
$X -bxor $Y
-bnot $X</
{{works with|PowerShell|3.0}}
<
# 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))</
=={{header|PureBasic}}==
<
Debug a & b ; And
Debug a | b ;Or
Line 4,790:
!mov dword [p.v_Temp], edx
Debug Temp
EndProcedure</
=={{header|Python}}==
Line 4,800:
binary output formatting in calculations and result displays.
<
mask = (1 << width) - 1
print(f"""\
Line 4,908:
if __name__ == '__main__':
bitwise_built_ins(8, 27, 125)
helper_funcs(8, 27)</
{{out}}
Line 4,966:
===Python 2===
<
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</
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:
<
x = x << n & 0xff
# ditto for 16 bit:
Line 4,985:
x = x << n & 0xffffffff
# ... and 64-bit:
x = x << n & 0xffffffffffffffff</
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.
<
"""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))</
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}}==
<
' no rotations and shift aritmetic are available in QB64
' Bitwise operator in Qbasic and QB64
Line 5,067:
Next
</syntaxhighlight>
=={{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>.
<
64 times
[ 2 /mod
Line 5,093:
say "bitwise RROTATE: " rrot64 echobin ] is task ( n n --> )
hex FFFFF hex F task</
{{out}}
Line 5,112:
=== Native functions in R 3.x ===
<
a <- 35
Line 5,121:
bitwNot(a)
bitwShiftL(a, 2)
bitwShiftR(a, 2)</
See also https://cran.r-project.org/doc/manuals/r-release/NEWS.3.html.
===Using ''as.hexmode'' or ''as.octmode''===
<
b <- as.hexmode(42)
as.integer(a & b) # 34
as.integer(a | b) # 43
as.integer(xor(a, b)) # 9</
===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.
<
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</
===Using ''bitops'' package===
<
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</
=={{header|Racket}}==
<
#lang racket
(define a 255)
Line 5,169:
(arithmetic-shift a b) ; left shift
(arithmetic-shift a (- b))) ; right shift
</syntaxhighlight>
Output:
<pre>
Line 5,178:
(formerly Perl 6)
{{works with|Rakudo|2017.05}}
<syntaxhighlight lang=raku
constant BITS = MAXINT.base(2).chars;
Line 5,205:
sub say_bit ($message, $value) {
printf("%30s: %{'0' ~ BITS}b\n", $message, $value +& MAXINT);
}</
{{out}}
<pre> 7: 0000000000000000000000000000000000000000000000000000000000000111
Line 5,232:
=={{header|Red}}==
<
a: 10
Line 5,249:
; there are no circular shift operators in Red
]
</syntaxhighlight>
{{out}}
<pre>
Line 5,266:
There is no predefined arithmetic shifts in Retro.
<
: bitwise ( ab- )
cr
Line 5,277:
2over << "a << b = %d\n" puts
2over >> "a >> b = %d\n" puts
2drop ;</
=={{header|REXX}}==
Line 5,290:
╚═══════════════════════════════════════════════════════════════════════════════════════╝
</pre>
<
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($))</
{{out|output}}
<pre>
Line 5,328:
=={{header|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>
=={{header|RLaB}}==
Line 5,345:
are integers then the result of the operation is an integer as well.
<
>> 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</
=={{header|Robotic}}==
<
input string "First value"
set "local1" to "input"
Line 5,376:
end
. "Bitwise rotation is not natively supported"
</syntaxhighlight>
=={{header|Ruby}}==
<
form = "%1$7s:%2$6d %2$016b"
puts form % ["a", a]
Line 5,391:
end
bitwise(14,3)</
{{out}}
Line 5,406:
=={{header|Rust}}==
<
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);
}</
Output:
Line 5,433:
=={{header|SAS}}==
<
data _null_;
a=105;
Line 5,444:
h=brshift(a,1);
put _all_;
run;</
=={{header|Scala}}==
<
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
}</
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^6</math>RS}}
<
(define (bitwise a b)
Line 5,476:
(newline))
(bitwise 255 5)</
Output:
<syntaxhighlight lang=text>5
255
250
-256
7</
''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.
<
include "bin32.s7i";
Line 5,523:
bitwise(65076, 6);
bitwise(bin32(65076), bin32(6));
end func;</
{{out}}
Line 5,544:
=={{header|Sidef}}==
<
say ('a and b : ', a & b)
say ('a or b : ', a | b)
Line 5,553:
}
bitwise(14,3)</
{{out}}
<pre>
Line 5,565:
=={{header|Simula}}==
<
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>
{{out}}
<pre>A AND B : 2
Line 5,680:
=={{header|Slate}}==
<
inform: (a bitAnd: b) printString.
Line 5,689:
inform: (a >> b) printString.
] applyTo: {8. 12}.</
'''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.
<
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 .</
in addition to the above,
{{works with|Smalltalk/X}}
<
(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"</
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:
<
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 *)
)</
More shifts are available for words (unsigned ints):
<
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 *)
)</
=={{header|Stata}}==
Line 5,746:
=={{header|Swift}}==
<
// All bitwise operations (including shifts)
// require both operands to be the same type
Line 5,760:
}
bitwise(-15,3)</
{{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:
<
initial begin
Line 5,793:
end
endprogram</
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:
<
parameter BITS = 32;
Line 5,808:
always_comb foreach (out[i]) out[i] = in[ (i+shift) % BITS ];
endmodule</
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.
<
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>
{{out}}
<pre>
Line 5,842:
=={{header|Tcl}}==
<
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}]]
}</
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):
<
set bits 0xFFFFFFFF
# Force interpretation as a 32-bit unsigned value
Line 5,863:
(($a >> (32-$b)) & ($bits ^ ($bits << $b)))
}]]
}</
=={{header|TI-89 BASIC}}==
Line 5,871:
The right shift operation fills the new leftmost bit with a copy of the old leftmost bit.
<
Prgm
Local show, oldbase
Line 5,893:
show("RRo ", rotate(a,–b))
setMode("Base",oldbase)
EndPrgm</
=={{header|Vala}}==
<
print(@"input: a = $a, b = $b\n");
print(@"AND: $a & $b = $(a & b)\n");
Line 5,912:
int b = 2;
testbit(a,b);
}</
{{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").
<
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>
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.
<
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</
Examples
<
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>
=={{header|Visual Basic}}==
Line 6,036:
=={{header|Visual Basic .NET}}==
<
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</
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.
<
var rr = Fn.new { |x, y| x >> y | x << (32-y) }
Line 6,075:
}
bitwise.call(10, 2)</
{{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)
<
global main
Line 6,197:
_null db 0
end</
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<
PROGRAM "bitwise"
Line 6,243:
END FUNCTION
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 6,270:
=={{header|XLISP}}==
<
; 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)))) )</
=={{header|XPL0}}==
<
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);</
The reason the "!" and "|" symbols may seem reversed is that the OR
Line 6,298:
=={{header|Yabasic}}==
<
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))</
<pre>6 = 00000110
3 = 00000011
Line 6,320:
=={{header|Z80 Assembly}}==
;AND
<
AND &1F ;0x05 & 0x1F</
;OR
<
OR &1F ;0x05 | 0x1F</
;XOR
<
XOR &1F ;0x05 ^ 0x1F</
;NOT
<
CPL</
;Left Shift (Z80 can only shift by one at a time.)
<
SLA A</
;Right Shift
<
SRL A</
;Arithmetic Right Shift
<
SRA A</
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.
<
RLA
Line 6,361:
LD A,&05
RRCA</
Line 6,367:
=={{header|zkl}}==
No bitwise rotates. Shifts are unsigned.
<
(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</
|