Bitwise operations: Difference between revisions

Add Ecstasy example
m (Automated syntax highlighting fixup (second round - minor fixes))
(Add Ecstasy example)
Line 2,889:
*/
</syntaxhighlight>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module BitwiseOps
{
@Inject Console console;
void run()
{
for ((Int n1, Int n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF]) // <- test data
{
static String hex(Int 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.println($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
| {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
| {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
| {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
| NOT {hex(n1)} = {hex(~n1)}
| left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
| right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
| right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
| left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
| right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
| leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
| rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
| leading zero count of {hex(n1)} = {n1.leadingZeroCount}
| trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
| bit count (aka "population") of {hex(n1)} = {n1.bitCount}
| reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
| reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
|
);
}
}
}
</syntaxhighlight>
 
Results in (extracted for just one of the test values):
<syntaxhighlight>
For values 1 (0x01) and 5 (0x05):
0x01 AND 0x05 = 0x01
0x01 OR 0x05 = 0x05
0x01 XOR 0x05 = 0x04
NOT 0x01 = 0xFFFFFFFFFFFFFFFE
left shift 0x01 by 5 = 0x20
right shift 0x01 by 5 = 0x00
right arithmetic shift 0x01 by 5 = 0x00
left rotate 0x01 by 5 = 0x20
right rotate 0x01 by 5 = 0x0800000000000000
leftmost bit of 0x01 = 0x01
rightmost bit of 0x01 = 0x01
leading zero count of 0x01 = 63
trailing zero count of 0x01 = 0
bit count (aka "population") of 0x01 = 1
reversed bits of 0x01 = 0x8000000000000000
reverse bytes of 0x01 = 0x0100000000000000
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x :
162

edits