I would like to be able to convert from a hex byte to an 8 bit binary string or bit array, modify a single bit in the string and convert back into a hex byte.
In theory i would have the input of
"FF"
convert it to binary and change one of the bits
"11111111" => "11110111"
and convert it back
"F7"
I cant get Convert.ToInt32() to work properly and Format("X2") wont work either. Any ideas?
private void changeDObit(int port, int bitNum, int state)
{
try
{
byte currentstate;
instantDoCtrl1.Read(port, out currentstate);
string data0Hex = currentstate.ToString("X2");
string data0Binary = Convert.ToString(Convert.ToInt32(data0Hex, 16), 2).PadLeft(data0Hex.Length * 4, '0');
if (!data0Binary[bitNum].Equals(state))
{
StringBuilder sb = new StringBuilder(data0Binary);
sb[bitNum] = (char)state;
data0Binary = sb.ToString();
string strHex = string.Format("{0:X2}", sb);
byte outdata = Convert.ToByte(strHex);
instantDoCtrl1.Write(port, outdata);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
0xff & 0xf7=>0xf7b = b & ~8.stringsto do it! If you want to check for even number make sure you use this method thedailywtf.com/Articles/An-Odd-Way-to-Find-Even-Numbers.aspx