How to read and write bits in C#
I have to write and read bits from int in my program. How to do it?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Jul 17, 2008, 12:51 PM
If performance is not a major consideration (as I'm using string conversions), then here are some easy to use bit functions written in C# :
using System;
class Bits
{
static void Main()
{
int i = 255; // or whatever
string bits = ConvertToBits(i);
Console.WriteLine("Bit representation of {0} is {1}", i, bits);
int j = GetBit(i, 1);
Console.WriteLine("Bit 1 is {0}", j);
Console.WriteLine("Setting bit 1 to 0");
SetBit(ref i, 1, 0);
Console.WriteLine("i is now {0}", i);
bits = ConvertToBits(i);
Console.WriteLine("Bit representation of {0} is {1}", i, bits);
j = GetBit(i, 2);
Console.WriteLine("Bit 2 is {0}", j);
Console.WriteLine("Flipping bit 2");
FlipBit(ref i, 2);
Console.WriteLine("i is now {0}", i);
bits = ConvertToBits(i);
Console.WriteLine("Bit representation of {0} is {1}", i, bits);
Console.ReadLine();
}
public static string ConvertToBits(int i)
{
string bits = Convert.ToString(i, 2);
int len = bits.Length;
if (len == 32)
{
return bits;
}
return new string('0', 32 - len) + bits;
}
public static int ConvertFromBits(string bits)
{
return Convert.ToInt32(bits, 2);
}
public static int GetBit(int i, int bitNum)
{
if (bitNum < 0 || bitNum > 31) return -1; // error value
return ConvertToBits(i)[31 - bitNum] - 48;
}
public static void SetBit(ref int i, int bitNum, int value)
{
if (bitNum < 0 || bitNum > 31 || value < 0 || value > 1) return; // i unchanged
char[] bitArray = ConvertToBits(i).ToCharArray();
bitArray[31 - bitNum] = (char)(value + 48);
i = Convert.ToInt32(new string(bitArray), 2);
}
public static void FlipBit(ref int i, int bitNum)
{
if (bitNum < 0 || bitNum > 31) return; // i unchanged
char[] bitArray = ConvertToBits(i).ToCharArray();
bitArray[31 - bitNum] = (bitArray[31 - bitNum] == '1') ? '0' : '1';
i = Convert.ToInt32(new string(bitArray), 2);
}
}
Raj KumarPosted Jul 17, 2008, 10:50 AM
Hope this will help.
http://local.wasp.uwa.edu.au/~pbourke/dataformats/bmp/BITMAP.C