Bitwise operations: Difference between revisions

m
m (→‎{{header|Perl}}: future-proof for 5.36, explicit :prototype)
 
(21 intermediate revisions by 11 users not shown)
Line 15:
print(‘x = ’x)
print(‘y = ’y)
print(‘NOT x = ’(-)~x))
print(‘x AND y = ’(x [&] y))
print(‘x OR y = ’(x [|] y))
Line 36:
x ROR y = -2147483646
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Bitwise operations 15/02/2017
Line 336 ⟶ 337:
MOVE.W #$04,D1
ROXR.W D1,D0</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program bitwise64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/************************************/
/* Initialized data */
/************************************/
.data
szMessResultAnd: .asciz "Result of And : \n"
szMessResultOr: .asciz "Result of Or : \n"
szMessResultEor: .asciz "Result of Exclusif Or : \n"
szMessResultNot: .asciz "Result of Not : \n"
szMessResultLsl: .asciz "Result of left shift : \n"
szMessResultLsr: .asciz "Result of right shift : \n"
szMessResultAsr: .asciz "Result of Arithmetic right shift : \n"
szMessResultRor: .asciz "Result of rotate right : \n"
szMessResultClear: .asciz "Result of Bit Clear : \n"
 
sMessAffBin: .ascii "Register: "
sZoneBin: .space 65,' '
.asciz "\n"
/************************************/
/* code section */
/************************************/
.text
.global main
main:
ldr x0,qAdrszMessResultAnd
bl affichageMess
mov x0,#5
and x0,x0,#15
 
bl affichage2
ldr x0,qAdrszMessResultOr
bl affichageMess
mov x0,#5
orr x0,x0,#15
bl affichage2
ldr x0,qAdrszMessResultEor
bl affichageMess
mov x0,#5
eor x0,x0,#15
bl affichage2
ldr x0,qAdrszMessResultNot
bl affichageMess
mov x0,#5
mvn x0,x0
bl affichage2
ldr x0,qAdrszMessResultLsl
bl affichageMess
mov x0,#5
lsl x0,x0,#1
bl affichage2
ldr x0,qAdrszMessResultLsr
bl affichageMess
mov x0,#5
lsr x0,x0,#1
bl affichage2
ldr x0,qAdrszMessResultAsr
bl affichageMess
mov x0,#-5
bl affichage2
mov x0,#-5
asr x0,x0,#1
bl affichage2
ldr x0,qAdrszMessResultRor
bl affichageMess
mov x0,#5
ror x0,x0,#1
bl affichage2
 
ldr x0,qAdrszMessResultClear
bl affichageMess
mov x0,0b1111
bic x0,x0,#0b100 // clear 3ieme bit
bl affichage2
mov x0,0b11111
bic x0,x0,#6 // clear 2ieme et 3ième bit ( 6 = 110 binary)
bl affichage2
 
100:
mov x0, #0
mov x8,EXIT
svc 0
qAdrszMessResultAnd: .quad szMessResultAnd
qAdrszMessResultOr: .quad szMessResultOr
qAdrszMessResultEor: .quad szMessResultEor
qAdrszMessResultNot: .quad szMessResultNot
qAdrszMessResultLsl: .quad szMessResultLsl
qAdrszMessResultLsr: .quad szMessResultLsr
qAdrszMessResultAsr: .quad szMessResultAsr
qAdrszMessResultRor: .quad szMessResultRor
qAdrszMessResultClear: .quad szMessResultClear
/******************************************************************/
/* display register in binary */
/******************************************************************/
/* x0 contains the register */
/* x1 contains the address of receipt area */
affichage2:
stp x1,lr,[sp,-16]! // save registers
ldr x1,qAdrsZoneBin
bl conversion2
ldr x0,qAdrsZoneMessBin
bl affichageMess
ldp x1,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
qAdrsZoneBin: .quad sZoneBin
qAdrsZoneMessBin: .quad sMessAffBin
/******************************************************************/
/* register conversion in binary */
/******************************************************************/
/* x0 contains the value */
/* x1 contains the address of receipt area */
conversion2:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x3,64 // position counter of the written character
2: // loop
tst x0,1 // test first bit
lsr x0,x0,#1 // shift right one bit
bne 3f
mov x2,#48 // bit = 0 => character '0'
b 4f
3:
mov x2,#49 // bit = 1 => character '1'
4:
strb w2,[x1,x3] // character in reception area at position counter
subs x3,x3,#1 // 0 bits ?
bgt 2b // no! loop
 
100:
ldp x3,x4,[sp],16 // restaur 2 registres
ldp x2,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
Result of And :
Register: 0000000000000000000000000000000000000000000000000000000000000101
Result of Or :
Register: 0000000000000000000000000000000000000000000000000000000000001111
Result of Exclusif Or :
Register: 0000000000000000000000000000000000000000000000000000000000001010
Result of Not :
Register: 1111111111111111111111111111111111111111111111111111111111111010
Result of left shift :
Register: 0000000000000000000000000000000000000000000000000000000000001010
Result of right shift :
Register: 0000000000000000000000000000000000000000000000000000000000000010
Result of Arithmetic right shift :
Register: 1111111111111111111111111111111111111111111111111111111111111011
Register: 1111111111111111111111111111111111111111111111111111111111111101
Result of rotate right :
Register: 1000000000000000000000000000000000000000000000000000000000000010
Result of Bit Clear :
Register: 0000000000000000000000000000000000000000000000000000000000001011
Register: 0000000000000000000000000000000000000000000000000000000000011001
</pre>
=={{header|ABAP}}==
This works in ABAP 7.40 and above. The missing arithmetic shift operations have been implemented with arithmetic, whereas the logical shift and the rotate operations have been implemented using the built in string functions shift_left and shift_right.
Line 2,673 ⟶ 2,849:
;;There is no built-in for rotation.</syntaxhighlight>
=={{header|COBOL}}==
{{Works with|COBOL 2023}}
Results are displayed in decimal.
COBOL 2002 added support for bitwise operations. Shift and rotation operators were added in COBOL 2023. Results are displayed in decimal.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. bitwise-ops.
Line 2,681 ⟶ 2,858:
01 a PIC 1(32) USAGE BIT.
01 b PIC 1(32) USAGE BIT.
 
01 result PIC 1(32) USAGE BIT.
01 result-disp REDEFINES result PIC S9(9) COMP.
PIC S9(9) USAGE COMPUTATIONAL.
 
LINKAGE SECTION.
01 a-int USAGE BINARY-LONG.
Line 2,705 ⟶ 2,881:
DISPLAY "a exclusive-or b is " result-disp
 
*> More complex *> COBOL does notoperations havecan shiftbe orconstructed rotationfrom operatorsthese.
 
GOBACKCOMPUTE result = B-NOT (a B-XOR b)
DISPLAY "Logical equivalence of a and b is " result-disp
.</syntaxhighlight>
 
COMPUTE result = (B-NOT a) B-AND b
DISPLAY "Logical implication of a and b is " result-disp
 
*> Shift and rotation operators were only added in COBOL 2023.
 
COMPUTE result = a B-SHIFT-L b
DISPLAY "a shifted left by b is " result-disp
 
COMPUTE result = b B-SHIFT-R a
DISPLAY "b shifted right by a is " result-disp
 
COMPUTE result = a B-SHIFT-LC b
DISPLAY "a rotated left by b is " result-disp
 
COMPUTE result = b B-SHIFT-RC a
DISPLAY "b rotated right by a is " result-disp
 
GOBACK.
 
END PROGRAM bitwise-ops.</syntaxhighlight>
 
{{works with|GnuCOBOL}}
{{works with|Visual COBOL}}
In older implementations, non-standard extensions were developed as built-in subroutines.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. mf-bitwise-ops.
 
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 result USAGE BINARY-LONG.
 
78 arg-len VALUE LENGTH OF result.
 
LINKAGE SECTION.
01 a USAGE BINARY-LONG.
01 b USAGE BINARY-LONG.
 
PROCEDURE DIVISION USING a, b.
main-line.
Line 2,729 ⟶ 2,927:
CALL "CBL_AND" USING a, result, VALUE arg-len
DISPLAY "a and b is " result
 
MOVE b TO result
CALL "CBL_OR" USING a, result, VALUE arg-len
DISPLAY "a or b is " result
 
MOVE a TO result
CALL "CBL_NOT" USING result, VALUE arg-len
DISPLAY "Not a is " result
 
MOVE b TO result
CALL "CBL_XOR" USING a, result, VALUE arg-len
DISPLAY "a exclusive-or b is " result
 
MOVE b TO result
CALL "CBL_EQ" USING a, result, VALUE arg-len
DISPLAY "Logical equivalence of a and b is " result
 
MOVE b TO result
CALL "CBL_IMP" USING a, result, VALUE arg-len
DISPLAY "Logical implication of a and b is " result
 
GOBACK.
 
.</syntaxhighlight>
END PROGRAM mf-bitwise-ops.</syntaxhighlight>
 
=={{header|CoffeeScript}}==
CoffeeScript provides sugar for some JavaScript operators, but the bitwise operators are taken directly from JS. See more here: http://coffeescript.org/#operators
Line 2,892 ⟶ 3,092:
`)
}</syntaxhighlight>
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
# numbers are doubles, bit operations use 32 bits and are unsigned
x = 11
y = 2
print bitnot x
print bitand x y
print bitor x y
print bitxor x y
print bitshift x y
print bitshift x -y
</syntaxhighlight>
 
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
Line 2,927 ⟶ 3,140:
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module BitwiseOps {
{
@Inject Console console;
void run() {
for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF]) { // <- test data
{
static String hex(Int64 n) { // <- this is a locally scoped helper function
for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF]) // <- test data
{
static String hex(Int64 n) // <- this is a locally scoped helper function
{
// formats the integer as a hex string, but drops the leading '0' bytes
return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
}
 
console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
Line 2,959 ⟶ 3,168:
|
);
}
}
}
}
</syntaxhighlight>
 
Line 2,987 ⟶ 3,196:
 
=={{header|Elena}}==
ELENA 46.x :
<syntaxhighlight lang="elena">import extensions;
 
Line 2,994 ⟶ 3,203:
bitwiseTest(y)
{
console.printLine(self," and ",y," = ",self.and( & y));
console.printLine(self," or ",y," = ",self.or( | y));
console.printLine(self," xor ",y," = ",self.xor( ^ y));
console.printLine("not ",self," = ",self.InvertedBInverted);
console.printLine(self," shr ",y," = ",self.shiftRight(y));
console.printLine(self," shl ",y," = ",self.shiftLeft(y));
Line 3,016 ⟶ 3,225:
255 shl 2 = 1020
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Bitwise_operation do
Line 3,692 ⟶ 3,902:
alert("a >>> b: " + (a >>> b)); // logical right shift
}</syntaxhighlight>
=={{header|jq}}==
'''Works with jq, the C implementation of jq'''
 
'''Works with gojq, the Go implementation of jq'''
 
jq has no built-in bitwise operations, but the
[[:Category:Jq/bitwise.jq | "bitwise" module]]
defines
all those needed for the task at hand except for rotations.
Here `rotateLeft` and rotateRight` functions are defined relative to a given width.
 
The examples are taken from the entry for [[#Wren|Wren]].
<syntaxhighlight lang="jq">
include "bitwise" {search: "."}; # adjust as required
 
def leftshift($n; $width):
[(range(0,$n)| 0), limit($width - $n; bitwise)][:$width] | to_int;
 
# Using a width of $width bits: x << n | x >> ($width-n)
def rotateLeft($x; $n; $width):
$x | bitwise_or(leftshift($n; $width); rightshift($width-$n));
 
# Using a width of $width bits: x << n | x >> ($width-n)
def rotateRight($x; $n; $width):
$x | bitwise_or(rightshift($n); leftshift($width-$n; $width) );
 
def task($x; $y):
def isInteger: type == "number" and . == round;
if ($x|isInteger|not) or ($y|isInteger|not) or
$x < 0 or $y < 0 or $x > 4294967295 or $y > 4294967295
then "Operands must be in the range of a 32-bit unsigned integer" | error
else
" x = \($x)",
" y = \($y)",
" x & y = \(bitwise_and($x; $y))",
" x | y = \(bitwise_or($x; $y))",
" x ^ y = \(null | xor(x; $y))",
"~x = \(32 | flip($x))",
" x << y = \($x | leftshift($y))",
" x >> y = \($x | rightshift($y))",
" x rl y = \(rotateLeft($x; $y; 32))",
" x rr y = \(rotateRight($x; $y; 32))"
end;
 
task(10; 2)
</syntaxhighlight>
{{output}}
<pre>
x = 10
y = 2
x & y = 2
x | y = 10
x ^ y = 8
~x = 4294967295
x << y = 40
x >> y = 2
x rl y = 40
x rr y = 2147483650
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia"># Version 5.2
Line 3,724 ⟶ 3,994:
rol(A,5) = Bool[true,true,false,false,true]
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
Line 5,360 ⟶ 5,631:
. "Bitwise rotation is not natively supported"
</syntaxhighlight>
=={{header|RPL}}==
≪ { AND OR XOR NOT SL SR ASR RL RR } → a b ops
≪ {} 1 ops SIZE '''FOR''' j
a →STR " " + '''IF''' j 3 ≤ '''THEN''' b →STR + " " + '''END'''
ops j GET →STR 2 OVER SIZE 1 - SUB + " -> " +
a j 3 ≤ b IFT ops j GET EVAL →STR + +
'''NEXT'''
≫ ≫ ‘'''BITOPS'''’ STO
{{out}}
<pre>
{ "# 355h # 113h AND -> # 111h"
"# 355h # 113h OR -> # 357h"
"# 355h # 113h XOR -> # 246h"
"# 355h NOT -> # FCAAh"
"# 355h SL -> # 6AAh"
"# 355h SR -> # 1AAh"
"# 355h ASR -> # 1AAh"
"# 355h RL -> # 6AAh"
"# 355h RR -> # 81AAh" }
</pre>
Operations made with a word size set at 16 bits.
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">def bitwise(a, b)
Line 5,386 ⟶ 5,679:
a >> b : 1 0000000000000001
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
Line 5,425 ⟶ 5,719:
put _all_;
run;</syntaxhighlight>
 
=={{header|S-BASIC}}==
S-BASIC does not have bitwise shift or rotate operators. The test values are taken from the 11l example.
<syntaxhighlight lang="BASIC">
var a, b = integer
a = 10
b = 2
print "a ="; a; tab(16); hex$(a)
print "b ="; b; tab(16); hex$(b)
print "a and b ="; a and b; tab(16); hex$(a and b)
print "a or b ="; a or b; tab(16); hex$(a or b)
print "a xor b ="; a xor b; tab(16); hex$(a xor b)
print "not a ="; not a; tab(16); hex$(not a)
 
end
</syntaxhighlight>
{{out}}
<pre>
a = 10 000A
b = 2 0002
a and b = 2 0002
a or b = 10 000A
a xor b = 688 02CD
not a =-11 FFF5
</pre>
 
=={{header|Scala}}==
 
Line 5,438 ⟶ 5,758:
println("a rol b: " + Integer.rotateRight(a, b)) // Rotate Right
}</syntaxhighlight>
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^6</math>RS}}
Line 5,897 ⟶ 6,218:
setMode("Base",oldbase)
EndPrgm</syntaxhighlight>
=={{header|Uxntal}}==
<syntaxhighlight lang="Uxntal">|00 @System [ &vector $2 &wst $1 &rst $1 &eaddr $2 &ecode $1 &pad $1 &r $2 &g $2 &b $2 &debug $1 &halt $1 ]
|10 @Console [ &vector $2 &read $1 &pad $5 &write $1 &error $1 ]
 
( program )
|0100 @on-reset ( -> )
#0a02
DUP2 SWP ;Labels/a <print-arg> ;Labels/b <print-arg>
bitwise
halt
BRK
 
@bitwise ( a b -- )
;Labels/not <print-str> ;Labels/a <print-str> ;Labels/equ <print-str> DUP2 [ POP #ff EOR ] <print-result>
;Labels/and <print-label> DUP2 [ AND ] <print-result>
;Labels/or <print-label> DUP2 [ ORA ] <print-result>
;Labels/xor <print-label> DUP2 [ EOR ] <print-result>
;Labels/shl <print-label> DUP2 [ #40 SFT SFT ] <print-result>
;Labels/shr <print-label> DUP2 [ SFT ] <print-result>
;Labels/rol <print-label> DUP2 [ #40 SFT #00 ROT ROT SFT2 ORA ] <print-result>
;Labels/ror <print-label> [ SWP #00 ROT SFT2 ORA ] <print-result>
JMP2r
 
@halt ( -- )
#01 .System/halt DEO
BRK
 
@<print-arg> ( a name* -- )
<print-str> ;Labels/equ <print-str> <print-result>
JMP2r
 
@<print-result> ( a -- )
<print-hex> ;Labels/newline <print-str>
JMP2r
 
@<print-label> ( label* -- )
;Labels/a <print-str>
<print-str>
;Labels/b <print-str>
;Labels/equ <print-str>
JMP2r
 
@<print-hex> ( byte -- )
[ LIT "$ ] .Console/write DEO
DUP #04 SFT <print-hex>/l
&l ( -- )
#0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO
JMP2r
 
@<print-str> ( str* -- )
&while ( -- )
LDAk .Console/write DEO
INC2 LDAk ?&while
POP2 JMP2r
 
@Labels
&a "a 20 $1
&b "b 20 $1
&equ "= 20 $1
&newline 0a $1
&not "NOT 20 $1
&and "AND 20 $1
&or "OR 20 $1
&xor "XOR 20 $1
&shl "SHL 20 $1
&shr "SHR 20 $1
&rol "ROL 20 $1
&ror "ROR 20 $1
</syntaxhighlight>
{{out}}
<pre>a = $0a
b = $02
NOT a = $f5
a AND b = $02
a OR b = $0a
a XOR b = $08
a SHL b = $28
a SHR b = $02
a ROL b = $28
a ROR b = $82
</pre>
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">void testbit(int a, int b) {
Line 6,053 ⟶ 6,456:
 
Given this limitation, there is no difference between logical and arithmetic left and right shift operations. Although Wren doesn't support circular shift operators, it is not difficult to write functions to perform them.
<syntaxhighlight lang="ecmascriptwren">var rl = Fn.new { |x, y| x << y | x >> (32-y) }
 
var rr = Fn.new { |x, y| x >> y | x << (32-y) }
Line 6,088 ⟶ 6,491:
x rr y = 2147483650
</pre>
 
=={{header|x86 Assembly}}==
{{works with|nasm}}
2,442

edits