/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Display the bits within a byte.
using System;
public class ShowBits {
public static void Main() {
int t;
byte val;
val = 123;
for(t=128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write("1 ");
if((val & t) == 0) Console.Write("0 ");
}
}
}
Language Basics
Use bitwise AND to determine if a number is odd
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use bitwise AND to determine if a number is odd.
using System;
public class IsOdd {
public static void Main() {
ushort num;
num = 10;
if((num & 1) == 1)
Console.WriteLine("This won't display.");
num = 11;
if((num & 1) == 1)
Console.WriteLine(num + " is odd.");
}
}
Use bitwise AND to make a number even
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use bitwise AND to make a number even.
using System;
public class MakeEven {
public static void Main() {
ushort num;
ushort i;
for(i = 1; i <= 10; i++) { num = i; Console.WriteLine("num: " + num); num = (ushort) (num & 0xFFFE); // num & 1111 1110 Console.WriteLine("num after turning off bit zero: " + num + " "); } } } [/csharp]
Shift Operators 2
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
*/
using System;
namespace Client.Chapter_2___Operators_and_Excpressions
{
public class ShiftOperators
{
static void Main(string[] args)
{
uint a = 0;
uint b = 0;
a = 8 << 3;
b = 32 >> 4;
}
}
}
Bit Shift operator
using System;
class CompoundBitOpsApp
{
static void Main(string[] args)
{
for (byte j = 0; j < 8; j++)
{
byte k = 1;
Console.WriteLine(
"1 <<= {0,3} ({1}) = {2,8} ({3,3})",
Convert.ToString(j, 2), j,
Convert.ToString((k <<= j), 2), k);
}
}
}
[/csharp]
Bit and, or, xor, not operator
using System;
class LogOpsApp
{
public static void display(byte left, byte right, byte ans, string op) {
string Lstr = null;
string Rstr = null;
string Astr = null;
Lstr = Convert.ToString(left, 2);
if (0 != right)
Rstr = Convert.ToString(right, 2);
else
Rstr = "--------";
Astr = Convert.ToString(ans, 2);
Console.WriteLine(" {0,8}
{1} {2,8}
{3,8}
",Lstr, op, Rstr, Astr);
}
static void Main(string[] args)
{
byte a, b, c, d, e, f, g;
a = 255;
b = 132;
c = 85;
byte OneOperand = 0;
d = (byte)(a & b);
display (a, b, d, "&");
e = (byte)(d | c);
display (d, c, e, "|");
f = (byte)(e ^ a);
display (e, a, f, "^");
g = (byte)~f;
display (f, OneOperand, g, "~");
}
}
Bit move operator
using System;
class Operators {
static void Main() {
int a = 256, b = 128, c, d;
c = a >> 1;
d = b << 1;
Console.WriteLine("{0}", c); //128
Console.WriteLine("{0}", d); //256
}
}
[/csharp]