If a byte is 192 or any other value, is there a way to show how it is made up of its individual bit values?


If a byte is 192 or any other value, is there a way to show how it is made up of its individual bit values?



For example,



If a byte is 192, I know this will be 128 + 64 = 192



Is there a way in CSharp to list the values that make up the byte so they can be printed or used elsewhere?



Thanks





"Yes, that's possible" and "What code has been tried / how is it not working?" There are plenty of questions/answers already on the topic..
– user2864740
Jun 29 at 7:10





2 Answers
2



Sample code:


int V = 192;
int B = 1;
for (int i=0; i<8; i++) {
if (V&0x01 == 1) {
// Use B any way you like
}
V/=2;
B*=2;
}



Try following :


static string ToBinary(int input)
{
string binary = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" };

return string.Join("", input.ToString("x").Select(x => binary[byte.Parse(x.ToString(), System.Globalization.NumberStyles.HexNumber)]));
}



Or use following


static string ToBinary2(int input)
{
List<string> results = new List<string>(); ;
while (input > 1)
{
results.Insert(0,(input % 2) == 0 ? "0" : "1");
input /= 2;
}
return string.Join("", results) ;

}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV