Binary literals C# with Example



Binary literals C# with Example

The 0b prefix can be used to represent Binary literals. 
 

Binary literals allow constructing numbers from zeroes and ones, which makes seeing which bits are set in the 
binary representation of a number much easier. This can be useful for working with binary flags. 
The following are equivalent ways of specifying an int with value 34 (=25 + 21): 
// Using a binary literal: 
// bits: 76543210 
int a1 = 0b00100010; // binary: explicitly specify bits 
// Existing methods: 
int a2 = 0x22; // hexadecimal: every digit corresponds to 4 bits 
int a3 = 34; // decimal: hard to visualise which bits are set 
int a4 = (1 << 5) | (1 << 1); // bitwise arithmetic: combining non-zero bits 
Flags enumerations 
Before, specifying flag values for an enum could only be done using one of the three methods in this example: 
[Flags] 
public enum DaysOfWeek 
{ 
// Previously available methods: 
// decimal hex 
bit shifting 
Monday = 1, // = 0x01 = 1 << 0 
Tuesday = 2, // = 0x02 = 1 << 1 
// = 0x04 = 1 << 2 
Wednesday = 4, 
// = 0x08 = 1 << 3 
Thursday = 8, 
Friday = 16, // = 0x10 = 1 << 4 
// = 0x20 = 1 << 5 
Saturday = 32, 
Sunday = 64, // = 0x40 = 1 << 6 
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday, 
Weekends = Saturday | Sunday 
} 
With binary literals it is more obvious which bits are set, and using them does not require understanding 
hexadecimal numbers and bitwise arithmetic: 
[Flags] 
public enum DaysOfWeek 
{ 
Monday = 0b00000001, 
Tuesday = 0b00000010, 
Wednesday = 0b00000100, 
Thursday = 0b00001000, 
Friday = 0b00010000, 
Saturday = 0b00100000, 
Sunday = 0b01000000, 
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday, 
Weekends = Saturday | Sunday 
} 

0 Comment's

Comment Form

Submit Comment