Bitwise operations: Difference between revisions

From Rosetta Code
Content added Content deleted
(added C)
(Forth)
Line 13: Line 13:
printf("not a: %d\n", ~a);
printf("not a: %d\n", ~a);
}
}

=={{header|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 . ;


=={{header|Java}}==
=={{header|Java}}==

Revision as of 23:30, 18 November 2007

Task
Bitwise operations
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.

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 . ;

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