开发者

C# interview question [closed]

开发者 https://www.devze.com 2023-03-12 14:19 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and开发者_运维技巧cannot be reasonably answered in its current form.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and 开发者_运维技巧cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

In one of the interview, i got asked the following question but i am not sure what is that, Please help me to understand about the question

Use C# to turn an 4th and 7th bits of a said byte myFlag in which write most bit is first bit.


Each byte has 8 bits, which are either on (1) or off (0). So you'd want to turn on the specified bits, using the bitwise operators.


how about ORing with 72 (01001000) ?

myFlag  = myFlag | 72;


Assuming my interpretation is correct you are looking to use bit-wise operators to solve the problem. In order to ensure a particular bit is on use | with the bits set that you want set.

myFlag = myFlag | 0b00010010

Or equivalently

myFlag |= 18


If it helps to see the string of bytes, then you can use the Convert class to convert integers to bit strings and reverse to help visualise the effects of the bitwise OR. Below is a sample that creates a toggledOnFlag that has the bits toggled on. You could OR with the other bit string to switch them off.

var toggleBitsOn  = "01001000";
var toggleBitsOff = "10110111";
var toggle = Convert.ToInt32(toggleBitsOn, 2);

var toggledOnFlag = myFlag | toggle;
Console.WriteLine(Convert.ToString(toggledOnFlag, 2));


You didn't specify how to declare "myFlag", but this should be what you're looking for.

[Flags]
enum BitFlags : byte
{
    One = ( 1 << 0 ),
    Two = ( 1 << 1 ),
    Three = ( 1 << 2 ),
    Four = ( 1 << 3 ),
    Five = ( 1 << 4 ),
    Six = ( 1 << 5 ),
    Seven = ( 1 << 6 ),
    Eight = ( 1 << 7 )
}

static void Main(string[] args)
{
    BitFlags myFlag = BitFlags.Four | BitFlags.Seven;

    Console.WriteLine( Convert.ToString( ( byte ) myFlag, 2 ) );
}

Edit: Updated for C# clarity and used "Flags" attribute, which is probably more along the lines of what the interviewer was looking for.

0

精彩评论

暂无评论...
验证码 换一张
取 消