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.
Related
I am using a Flags Enum to track the completion stages of a data migration process for each data record. I need a way to reset back to a specified stage where I can begin reprocessing the migration of a data record. How does one reset the higher bytes in a Flags Enum?
Example Enum:
[Flags]
public Enum MigrationStages {
None = 0,
Started = 1,
MiddleStage = 2,
WrappingUp = 4,
Finished = 8
}
My current value:
var currentStage =
MigrationStages.None
| MigrationStages.Started
| MigrationStages.MiddleStage
| MigrationStages.WrappingUp
| MigrationStages.Finished;
I want to reset back to MigrationStages.MiddleStage to cause reprocessing to occur starting there.
Bitwise math is not something we use much anymore. As such, when I went searching for an answer to this I found nothing that helped so I worked it out. Sharing my math with the world in case others find it useful.
I created a simple helper method to do this, as follows:
public static MigrationStage ClearHigherFlags(MigrationStage orig, MigrationStage highBit)
{
var lowerBits = (int)orig % (int)highBit;
return highBit + lowerBits;
}
Usage example:
currentStage = ClearHigherFlags(currentStage, MigrationStages.MiddleStage);
Obviously, if you want to clear higher flags including the highBit, just don't add it back. To clear lower flags, return orig - lowerBits.
In bitwise math, modulus (%) is often your friend.
Addendum
There are those who will find this answer and think that it's not really bit math. I hope this assuages those folks.
First, recall that this is flags we're talking about so a very specific subset of bit manipulation where modulus makes the math easier to read and is very appropriate. The actual math performed by the compiler replacement will be something like what follows, which I find much less intuitive to read.
public static MigrationStage ClearHigherFlags(MigrationStage orig, MigrationStage highBit)
{
var bitMask = highBit - 1;
var lowerBits = orig & bitMask;
return highBit + lowerBits;
}
It's really not too hard to read but the conversion to a bit mask is done implicitly in my original solution.
If you want to use bitwise manipulation you can do it this way:
var lowbits = MigrationStages.MiddleStage | MigrationStages.Started;
Then to clear the high bits in your example:
currentStage = currentStage & lowbits;
Maybe this will make more sense:
8 4 2 1
==========
lowbits 0 0 1 1
currentvalue 1 1 1 1
==========
AND (&) 0 0 1 1
which clears the two high bits
This question already has answers here:
Why use the Bitwise-Shift operator for values in a C enum definition?
(9 answers)
Closed 6 years ago.
Ok so I am new to C#, and for the life of me I cannot comprehend what exactly the below code (from a legacy project) is supposed to do:
[Flags]
public enum EAccountStatus
{
None = 0,
FreeServiceApproved = 1 << 0,
GovernmentAccount = 1 << 1,
PrivateOrganisationAccount = 1 << 2,
All = 8
}
What exactly does the << operator do here on the enums? Why do we need this?
Behind the scenes, the enumeration is actually an int.
<< is the Bitwise Left Shift Operator
An equivalent way of writing this code is :
[Flags]
public enum EAccountStatus
{
None = 0,
FreeServiceApproved = 1,
GovernmentAccount = 2,
PrivateOrganisationAccount = 4,
All = 8
}
Please note, that this enumeration has the Flag attribute
As stated in the msdn:
Use the FlagsAttribute custom attribute for an enumeration only if a
bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a
numeric value.
This way, if you want to have multiple options set you can use:
var combined = EAccountStatus.FreeServiceApproved | EAccountStatus.GovernmentAccount
which is equivalent to:
00000001 // =1 - FreeServiceApproved
| 00000010 // =2 - GovernmentAccount
---------
00000011 //= 3 - FreeServiceApproved and GovernmentAccount
this SO thread has a rather good explanation about the flags attribute
<< is doing simply what does i.e. Shift left operation.
As far as why in an enum is concerned, its just a way of evaluating the expression as enums allow expressions (and evaluate them on compile time)
This question already has answers here:
A clear, layman's explanation of the difference between | and || in c#?
(11 answers)
Closed 8 years ago.
I need to take two bytes and OR them together, a rather simple task. However, I do not know the proper syntax to OR the two bytes together.
byte First = 0x03;
byte Second = 0x15;
//Need to or Them
byte Result = First || Second; //This syntax does not work in C#
You need | Operator
byte Result = (byte)(First | Second);
|| is a logical or not bitwise so you need:
byte Result = (byte) (First | Second);
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 10 years ago.
I am trying to write a chip8 emulator in C#. It will be necessary to simulate in software the operations that take place in hardware on the real chip.
There is an opcode that requires detecting a whether a borrow occurred during the subtraction of two binary numbers.
Byte1 - Byte2
Does anyone have any ideas as to how I can use C# to tell if a borrow occurred or not?
After searching in Wikipedia for the mysterious opcode you didn't mention, and looking for some implementations. I can conclude that the opcodes 8XY5 and 8XY7 (where X and Y are register identifiers) will do substractions.
For 8XY5 the register X will be set to the value of the register X minus the value of the register Y. And the register F will be set to 1 if the value of the register Y is greater or equal to the value of the register X (0 otherwise).
For 8XY7 the register X will be set to the value of the register Y minus the value of the register X. And the register F will be set to 1 if the value of the register X is greater or equal to the value of the register Y (0 otherwise).
This is the "pseudo"-code for 8XY5:
x = opcode[1]
y = opcode[2]
if (register[x] >= register[y])
register[0xF] = 1
else
register[0xF] = 0
result = register[x] - register[y]
if result < 0
result += 256
register[x] = result
and this is the "pseudo"-code for 8XY7:
x = opcode[1]
y = opcode[2]
if (register[y] >= register[x])
register[0xF] = 1
else
register[0xF] = 0
result = register[y] - register[x]
if result < 0
result += 256
register[x] = result
And here is a C# implementation:
const byte B_0 = 0x0;
const byte B_1 = 0x1;
const byte B_F = 0xF;
static void Main()
{
byte[] registers = new byte[16];
registers[0x1] = 255;
registers[0x2] = 127;
Opcode8XY5(registers, 1, 2);
Console.WriteLine(registers[0x1]);
Console.WriteLine(registers[0x2]);
Console.WriteLine(registers[0xF]);
Opcode8XY7(registers, 1, 2);
Console.WriteLine(registers[0x1]);
Console.WriteLine(registers[0x2]);
Console.WriteLine(registers[0xF]);
Console.ReadLine();
}
static void Opcode8XY5(byte[] registers, byte x, byte y)
{
registers[B_F] = registers[x] >= registers[y] ? B_1 : B_0;
registers[x] = (byte)(registers[x] - registers[y]);
}
static void Opcode8XY7(byte[] registers, byte x, byte y)
{
registers[B_F] = registers[y] >= registers[x] ? B_1 : B_0;
registers[x] = (byte)(registers[y] - registers[x]);
}
Check this implementation for reference.
You will need to compare each bit of the bytes... If the second byte bit is set but not the first, you have a borrow condition:
static void Main(string[] args) {
byte b1 = byte.Parse(args[0]);
byte b2 = byte.Parse(args[1]);
bool borrow = false;
for (int mask = 0x01; mask <= 0x80; mask <<= 1) {
if ((b2 & mask) > (b1 & mask)) {
borrow = true;
}
}
Console.WriteLine(Convert.ToString(b1, 2).PadLeft(8, '0'));
Console.WriteLine(Convert.ToString(b2, 2).PadLeft(8, '0'));
Console.WriteLine("borrowed: {0}", borrow);
}
There may be a very clever boolean logic that gives you the answer, but I cannot come up with it now.
You need to do the math with wider type provided that the typecast was not sign-propagating. Then check if the result has the 8th bit set to 1. If it is set then borrowing had place. Then save a result as byte.
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 10 years ago.
Here is my code:
long max = pcmU16.Length;
long index = 0;
fixed (ushort* srcFix = pcmU16)
{
ushort* src = srcFix;
next:
*src = 32768;
src++;
index++;
if (index != max)
{
goto next;
}
}
Like you see, it is writing 2 bytes at once. How to use ulong type and write 8 bytes at once? pcmU16 is ushort[] array.
You just coerce it:
ulong* src = (ulong*)srcFix;
Things to watch, though:
your max needs to be divided by 4, else you're going out of range
you need to handle any stray values - for example, say you have 10 ushort values (max was 10 initially); that is 2 sets of ulong (4 each), and a final 2 ushort; the usual divisor/remainder stuff
As a final note, you might find the index syntax more convenient, i.e.
for(int i = 0 ; i < max ; i++) {
src[i] = ...
}