IT

C # 이진 리터럴

lottoking 2020. 5. 23. 09:11
반응형

C # 이진 리터럴


16 진수 앞에 0x를 붙이는 것과 같이 C #에서 이진 리터럴을 작성하는 방법이 있습니까? 0b가 작동하지 않습니다.

그렇지 않은 경우 쉬운 방법은 무엇입니까? 어떤 종류의 문자열 변환?


C # 7.0이진 리터럴 (및 밑줄 문자를 통한 선택적 숫자 구분 기호)을 지원합니다.

예를 들면 :

int myValue = 0b0010_0110_0000_0011;

Roslyn GitHub 페이지 에서 자세한 정보를 확인할 수도 있습니다 .


최신 정보

C # 7.0에는 이제 이진 리터럴이 포함되어 있습니다.

[Flags]
enum Days
{
    None = 0,
    Sunday    = 0b0000001,
    Monday    = 0b0000010,   // 2
    Tuesday   = 0b0000100,   // 4
    Wednesday = 0b0001000,   // 8
    Thursday  = 0b0010000,   // 16
    Friday    = 0b0100000,   // etc.
    Saturday  = 0b1000000,
    Weekend = Saturday | Sunday,
    Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}

원본 게시물

이 주제는 열거 형에서 비트 기반 플래그 값을 선언하는 것으로 보였으 므로이 종류의 편리한 트릭을 지적 할 가치가 있다고 생각했습니다. 왼쪽 시프트 연산자 ( <<)를 사용하면 비트를 특정 이진 위치로 푸시 할 수 있습니다. 이를 같은 클래스의 다른 값으로 열거 형 값을 선언하는 기능과 결합하면 비트 플래그 열거 형에 대해 매우 읽기 쉬운 선언 구문이 있습니다.

[Flags]
enum Days
{
    None        = 0,
    Sunday      = 1,
    Monday      = 1 << 1,   // 2
    Tuesday     = 1 << 2,   // 4
    Wednesday   = 1 << 3,   // 8
    Thursday    = 1 << 4,   // 16
    Friday      = 1 << 5,   // etc.
    Saturday    = 1 << 6,
    Weekend     = Saturday | Sunday,
    Weekdays    = Monday | Tuesday | Wednesday | Thursday | Friday
}

정수와 16 진수 만 직접 사용합니다 (ECMA 334v4).

9.4.4.2 정수 리터럴 정수 리터럴은 int, uint, long 및 ulong 유형의 값을 쓰는 데 사용됩니다. 정수 리터럴에는 10 진수와 16 진수의 두 가지 가능한 형식이 있습니다.

파싱하려면 다음을 사용할 수 있습니다.

int i = Convert.ToInt32("01101101", 2);

열거 형의 비트 플래그에 대한 @StriplingWarrior의 답변에 덧붙여, 비트 시프트를 통해 위쪽으로 카운트하기 위해 16 진수로 사용할 수있는 쉬운 규칙이 있습니다. 1-2-4-8 순서를 사용하여 한 열을 왼쪽으로 이동 한 후 반복하십시오.

[Flags]
enum Scenery
{
  Trees   = 0x001, // 000000000001
  Grass   = 0x002, // 000000000010
  Flowers = 0x004, // 000000000100
  Cactus  = 0x008, // 000000001000
  Birds   = 0x010, // 000000010000
  Bushes  = 0x020, // 000000100000
  Shrubs  = 0x040, // 000001000000
  Trails  = 0x080, // 000010000000
  Ferns   = 0x100, // 000100000000
  Rocks   = 0x200, // 001000000000
  Animals = 0x400, // 010000000000
  Moss    = 0x800, // 100000000000
}

오른쪽 열부터 스캔하여 1-2-4-8 (shift) 1-2-4-8 (shift) 패턴을 확인하십시오.


원래 질문에 대답하기 위해 16 진수를 사용하는 @Sahuagin의 제안을 두 번째로하십시오. 이 문제를 우려하기에 충분한 이진수로 자주 작업하는 경우 16 진수를 익힐 가치가 있습니다.

소스 코드에서 이진수를 볼 필요가 있다면 위와 같이 이진 리터럴로 주석을 추가하는 것이 좋습니다.


다음과 같은 값을 포함하는 준 리터럴 상수를 항상 만들 수 있습니다.

const int b001 = 1;
const int b010 = 2;
const int b011 = 3;
// etc ...
Debug.Assert((b001 | b010) == b011);

자주 사용하는 경우 재사용을 위해 정적 클래스로 랩핑 할 수 있습니다.

However, slightliy off-topic, if you have any semantics associated with the bits (known at compile time) I would suggest using an Enum instead:

enum Flags
{ 
    First = 0,
    Second = 1,
    Third = 2,
    SecondAndThird = 3
}
// later ...
Debug.Assert((Flags.Second | Flags.Third) == Flags.SecondAndThird);

If you look at the language feature implementation status of the .NET Compiler Platform ("Roslyn") you can clearly see that in C# 6.0 this is a planned feature, so in the next release we can do it in the usual way.

Binary literal status


string sTable="static class BinaryTable\r\n{";
string stemp = "";
for (int i = 0; i < 256; i++)
{
stemp = System.Convert.ToString(i, 2);
while(stemp.Length<8) stemp = "0" + stemp;
sTable += "\tconst char nb" + stemp + "=" + i.ToString() + ";\r\n";
}
sTable += "}";
Clipboard.Clear();
Clipboard.SetText ( sTable);
MessageBox.Show(sTable);

Using this, for 8bit binary, I use this to make a static class and it puts it into the clipboard.. Then it gets pasted into the project and added to the Using section, so anything with nb001010 is taken out of a table, at least static, but still... I use C# for a lot of PIC graphics coding and use 0b101010 a lot in Hi-Tech C

--sample from code outpt--

static class BinaryTable
{   const char nb00000000=0;
    const char nb00000001=1;
    const char nb00000010=2;
    const char nb00000011=3;
    const char nb00000100=4;
//etc, etc, etc, etc, etc, etc, etc, 
}

:-) NEAL


Binary literal feature was not implemented in C# 6.0 & Visual Studio 2015. but on 30-March 2016 Microsoft announced the new version of Visual Studio '15' Preview with that we can use binary literals.

We can use one or more than one Underscore( _ ) character for digit separators. so the code snippet would look something like:

int x           = 0b10___10_0__________________00; //binary value of 80
int SeventyFive = 0B100_________1011; //binary value of 75

WriteLine($" {x} \n {SeventyFive}");

and we can use either of 0b and 0B as shown in the above code snippet.

if you do not want to use digit separator you can use it without digit separator like below code snippet

int x           = 0b1010000; //binary value of 80
int SeventyFive = 0B1001011; //binary value of 75

WriteLine($" {x} \n {SeventyFive}");

While not possible using a Literal, maybe a BitConverter can also be a solution?


Though the string parsing solution is the most popular, I don't like it, because parsing string can be a great performance hit in some situations.

When there is needed a kind of a bitfield or binary mask, I'd rather write it like

long bitMask = 1011001;

And later

int bit5 = BitField.GetBit(bitMask, 5);

Or

bool flag5 = BitField.GetFlag(bitMask, 5);`

Where BitField class is

public static class BitField
{
    public static int GetBit(int bitField, int index)
    {
        return (bitField / (int)Math.Pow(10, index)) % 10;
    }

    public static bool GetFlag(int bitField, int index)
    {
        return GetBit(bitField, index) == 1;
    }
}

You can use 0b000001 since Visual Studio 2017 (C# 7.0)


Basically, I think the answer is NO, there is no easy way. Use decimal or hexadecimal constants - they are simple and clear. @RoyTinkers answer is also good - use a comment.

int someHexFlag = 0x010; // 000000010000
int someDecFlag = 8;     // 000000001000

The others answers here present several useful work-a rounds, but I think they aren't better then the simple answer. C# language designers probably considered a '0b' prefix unnecessary. HEX is easy to convert to binary, and most programmers are going to have to know the DEC equivalents of 0-8 anyways.

Also, when examining values in the debugger, they will be displayed has HEX or DEC.

참고URL : https://stackoverflow.com/questions/594720/c-sharp-binary-literals

반응형