32 lines
1.8 KiB
Plaintext
32 lines
1.8 KiB
Plaintext
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
|
|
// 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)}):
|
|
| {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())}
|
|
|
|
|
);
|
|
}
|
|
}
|
|
}
|