Bitwise operations: Difference between revisions
(Added BASIC example.) |
(Added Haskell example) |
||
Line 56: | Line 56: | ||
cr ." a xor b = " over xor . |
cr ." a xor b = " over xor . |
||
cr ." not a = " invert . ; |
cr ." not a = " invert . ; |
||
=={{header|Haskell}}== |
|||
The operations in ''Data.Bits'' work on ''Int'', ''Integer'', and any of the sized integer and word types. |
|||
import Data.Bits |
|||
a = 255 |
|||
b = 170 |
|||
a_and_b = a .&. b |
|||
a_or_b = a .|. b |
|||
a_xor_b = a `xor` b |
|||
not_a = complement a |
|||
=={{header|Java}}== |
=={{header|Java}}== |
Revision as of 11:04, 19 November 2007
You are encouraged to solve this task according to the task description, using any language you may know.
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Write a function to perform a bitwise AND, OR, and XOR on two integers and perform a bitwise NOT on the first number.
Ada
The following program performs all required operations and prints the resulting values in base 2 for easy checking of the bit values.
with Ada.Text_Io; use Ada.Text_Io; procedure Bitwise is type Byte is mod 2**8; package Byte_Io is new Ada.Text_Io.Modular_Io(Byte); A : Byte := 255; B : Byte := 170; begin Put("A and B = "); Byte_Io.Put(Item => A and B, Base => 2); New_Line; Put("A or B = "); Byte_IO.Put(Item => A or B, Base => 2); New_Line; Put("A xor B = "); Byte_Io.Put(Item => A xor B, Base => 2); New_Line; Put("Not A = "); Byte_IO.Put(Item => not A, Base => 2); New_Line; end bitwise;
The output of this program is:
A and B = 2#10101010# A or B = 2#11111111# A xor B = 2#1010101# Not A = 2#0#
BASIC
Compiler: QuickBasic 4.5
SUB bitwise (a, b) PRINT a AND b PRINT a OR b PRINT a XOR b PRINT NOT a END SUB
C
void bitwise(int a, int b) { printf("a and b: %d\n", a & b); printf("a or b: %d\n", a | b); printf("a xor b: %d\n", a ^ b); printf("not a: %d\n", ~a); }
Forth
: bitwise ( a b -- ) cr ." a = " over . ." b = " dup . cr ." a and b = " 2dup and . cr ." a or b = " 2dup or . cr ." a xor b = " over xor . cr ." not a = " invert . ;
Haskell
The operations in Data.Bits work on Int, Integer, and any of the sized integer and word types.
import Data.Bits a = 255 b = 170 a_and_b = a .&. b a_or_b = a .|. b a_xor_b = a `xor` b not_a = complement a
Java
public static void bitwise(int a, int b){ System.out.println("a AND b: " + (a & b)); System.out.println("a OR b: "+ (a | b)); System.out.println("a XOR b: "+ (a ^ b)); System.out.println("NOT a: " + ~a); }
The call:
bitwise(4, 7);
will output:
a AND b: 4 a OR b: 7 a XOR b: 3 NOT a: -5