我如何找到二进制字符串 [英] How do I find a binary-string

查看:162
本文介绍了我如何找到二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序,我可以用一定的数字来编写以触发多个函数。

但是我无法确定何时使用某个数字。举个例子说我有数字10我想用某种算法自动将它改成二进制字符串(00001010)。之后我想知道哪些位是打开和关闭所以我可以调用不同的函数。

I'm trying to make a program where i can write in a certain number to trigger multiple functions.
But I'm having trouble identifying when a certain number is used. For an example say i have the number "10" i would like to change it to a binary string(00001010) automatically using an algorithm of some-sort. After that i would like to know which bits are on and off so i can call different functions.

推荐答案

你要找的术语不是字节形式 ,它是二进制或可能是二进制字符串。

转换它非常简单:

The term you are looking for is not "byte-form", it's "binary" or possibly "binary string".
Converting it is pretty easy:
int i = 10;
Console.WriteLine(Convert.ToString(i, 2).PadLeft(8, '0'));



但是你不需要将其转换为检查位:


But you don't need to convert it to check bits:

    int i = 10;
    for (int j = 7; j >= 0; j--)
        {
        Console.Write(BitValue(i, j));
        }
    Console.WriteLine();
    }
private int BitValue(int i, int bitNo)
    {
    return (i >> bitNo) & 1;
    }

或者甚至:

Or even:

    int i = 10;
    Console.WriteLine(Convert.ToString(i, 2).PadLeft(8, '0'));
    for (int j = 7; j >= 0; j--)
        {
        Console.Write(BitValue(i, j) ? '*' : '.');
        }
    Console.WriteLine();
    }
private bool BitValue(int i, int bitNo)
    {
    return (i & (1 << bitNo)) != 0;
    }


这篇关于我如何找到二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆