Bitwise operations: Difference between revisions

Updated D code
(Updated D code)
Line 320:
 
=={{header|D}}==
<lang d>module bitwiseimport std.stdio;
import std.stdio ;
 
voidT testbitrot(intT)(T ax, int bshift) {
writefln return ("Input:x >> ashift) =| %3d(x ,<< b(T.sizeof =* %3d",8 a,- bshift)) ;
writefln("AND : %8b & %08b = %032b (%4d)", a, b, a & b, a & b) ;
writefln(" OR : %8b | %08b = %032b (%4d)", a, b, a | b, a | b) ;
writefln("XOR : %8b ^ %08b = %032b (%4d)", a, b, a ^ b, a ^ b) ;
writefln("LSH : %8b << %08b = %032b (%4d)", a, b, a << b, a << b) ;
writefln("RSH : %8b >> %08b = %032b (%4d)", a, b, a >> b, a >> b) ;
writefln("NOT : %8s ~ %08b = %032b (%4d)", "", a, ~a, ~a) ;
}
 
// shift and rotation are not available
void testBit(int a, int b) {
writefln("Input: a = %d, b = %d", a, b);
writefln("AND : %8b & %08b = %032b (%4d)", a, b, a & b, a & b) ;
writefln(" OR : %8b | %08b = %032b (%4d)", a, b, a | b, a | b) ;
writefln("XOR : %8b ^ %08b = %032b (%4d)", a, b, a ^ b, a ^ b) ;
writefln("LSH : %8b << %08b = %032b (%4d)", a, b, a << b, a << b) ;
writefln("RSH : %8b >> %08b = %032b (%4d)", a, b, a >> b, a >> b) ;
writefln("NOT : %8s ~ %08b = %032b (%4d)", "", a, ~a, ~a) ;
writefln("ROT : rot(%8b, %d) = %032b (%4d)", a, b, rot(a,b), rot(a,b));
}
 
void main() {
int a = 0b11111111 0b_1111_1111; // bit literal 255
int b = 0b00000010 0b_0000_0010; // bit literal 2
 
testbittestBit(a, b) ;
}</lang>Output:
Output:
<pre>Input: a = 255 , b = 2
AND : 11111111 & 00000010 = 00000000000000000000000000000010 ( 2)
ORAND : 11111111 | & 00000010 = 0000000000000000000000001111111100000000000000000000000000000010 ( 255 2)
XOR OR : 11111111 ^ | 00000010 = 0000000000000000000000001111110100000000000000000000000011111111 ( 253255)
ANDXOR : 11111111 & ^ 00000010 = 0000000000000000000000000000001000000000000000000000000011111101 ( 2253)
LSH : 11111111 << 00000010 = 00000000000000000000001111111100 (1020)
RSH : 11111111 >> 00000010 = 00000000000000000000000000111111 ( 63)
NOT : ~ 11111111 = 11111111111111111111111100000000 (-256)</pre>
ROT : rot(11111111, 2) = 11000000000000000000000000111111 (-1073741761)</pre>
 
Compilers are usually able to optimize the code pattern of the rot function to one CPU instruction plus loads.
 
=={{header|Delphi}}==
Anonymous user