I know there is similar questions to my question, however, they aren't the same. All of them are just normal shifts, circular shifts etc. not having a through Carry flag.
I am trying to implement a method that does a right rotate through carry flag, carry flag being 1, current code:
public static int RotateRight(int value, int count = 2)
{
uint val = (uint)value;
return (int)((val >> count) | (val << (32 - count)));
}
However, this works only as normal shift, an input of 16 returns 4. How would one create a carry flag?
Before an admin points to this question C# bitwise rotate left and rotate right this does a normal rotate without a through carry flag.
Rotate through carry
Another example of this:
10 >> 2 with carry through flag of 1
1 00010000
Rotate with carry >> 2
0 10001000
0 01000100
If I'm understanding you correctly, here my really straigth-forward, off the top of my head, totally unoptimized way of doing it:
int RotateRightThroughCarry(uint value, int count, ref uint carry)
{
// width assumed to be 32 bits
// carry assumed to be either 0 or 1
for(int i = 0; i < count; i++)
value = RotateRightOneBitThroughCarry(value, ref carry);
return value;
}
int RotateRightOneBitThroughCarry(uint value, ref uint carry)
{
int newCarry = value & 1;
int newValue = (value >> 1) | (carry << 31);
carry = newCarry;
return newValue;
}
Related
So I've come across a strange need to 'merge' two numbers:
byte one;
byte two;
into an int three; with the first bit being the first bit of one, the second bit being the first bit of two, the third being the second bit of one and so on.
So with these two numbers:
01001000
00010001
would result in
0001001001000010
A more didatic illustration of the interlacing operation:
byte one = 0 1 0 0 1 0 0 0
byte two = 0 0 0 1 0 0 0 1
result = 00 01 00 10 01 00 00 10
UPDATE: Sorry misread your question completely.
The following code should do:
public static int InterlacedMerge(byte low, byte high)
{
var result = 0;
for (var offset = 0; offset < 8; offset++)
{
var mask = 1 << offset;
result |= ((low & mask) | ((high & mask)) << 1) << offset;
}
return result;
}
I am not, by any means, very smart when it comes to bit twiddling so there probably is a more efficient way to do this. That said, I think this will do the job but I haven't tested it, so make sure you do.
P.D: There are some unnecessary parenthesis in the code but I'm never sure about bitwise operators precedence so I find it easier to read the way its written.
UPDATE2: Here is the same code a little more verbose to make it easier to follow:
public static int InterlacedMerge(byte low, byte high)
{
var result = 0;
for (var offset = 0; offset < 8; offset++)
{
//Creates a mask with the current bit set to one: 00000001,
//00000010, 00000100, and so on...
var mask = 1 << offset;
//Creates a number with the current bit set to low's bit value.
//All other bits are 0
var lowAndMask = low & mask;
//Creates a number with the current bit set to high's bit value.
//All other bits are 0
var highAndMask = high & mask;
//Create a merged pair where the lowest bit is the low 's bit value
//and the highest bit is high's bit value.
var mergedPair = lowAndMask | (highAndMask << 1);
//Ors the mergedPair into the result shifted left offset times
//Because we are merging two bits at a time, we need to
//shift 1 additional time for each preceding bit.
result |= mergedPair << offset;
}
return result;
}
#inbetween answered while I was writing this; similar solution, different phrasing.
You'll have to write a loop. You'll test one bit in each of the two inputs. You'll set a bit in an output for each input. You'll shift all three values one place. Maybe something like this (untested):
#define TOPBIT 32768
for /* 16 times */
if ( value1 & 1 ) out |= TOPBIT;
out >>= 1;
if ( value2 & 1 ) out |= TOPBIT;
out >>= 1;
b1 >>= 1;
b2 >>= 1;
Quite often when using hardware interfaces you'll have to set groups of bits or set them without changing the rest of the bits. The interface description says something like:
you get a System.UINT32, bit 0 is set if available; bits 1..7 mean the minimum value; bits 8..14 is the maximum value; bits 15..17 is the threshold, etc.
I have to do this for a lot of values, each with their own start and stop bits.
That's why I'd like to create a class that can convert the values (start bit; stop bit; raw UINT32 value) into the value it represents, and back.
So something like:
class RawParameterInterpreter
{
public int StartBit {get; set;} // counting from 0..31
public int StopBit {get; set;} // counting from 0..31
Uint32 ExtractParameterValue(Uint32 rawValue);
Uint32 InsertParameterValueToRawValue(Uint32 parameterValue,
Uint32 rawValue);
}
I understand the part with handling the bits:
// example bits 4..7:
extract parameter from raw value: (rawvalue & 0x000000F0) >> startbit;
insert parameter into raw: (parameter << startbit) | (rawValue & 0xFFFFFF0F)
The problem is, how to initialize the 0x000000F0 and 0xFFFFFF0F from values startBit and endBit? Is there a general method to calculate these values?
I would use something like this
Uint32 bitPattern = 0;
for (int bitNr = startBit; bitNr <= stopBit; ++bitNr)
{
bitPattern = bitPattern << 2 + 1;
}
bitPattern = bitPattern << startBit;
I know the class System.Collections.BitArray. This would make it even easier to set the bits, but how to convert the BitArray back to Uint32?
So question: what is the best method for this?
Well, your question is very general but,
You could use an enum with a Flags attribute.
[Flags]
public enum BitPattern
{
Start = 1,
Stop = 1 << 31
}
I need to mask certain string values read from a database by setting a specific bit in an int value for each possible database value. For example, if the database returns the string "value1" then the bit in position 0 will need to be set to 1, but if the database returns "value2" then the bit in position 1 will need to be set to 1 instead.
How can I ensure each bit of an int is set to 0 originally and then turn on just the specified bit?
If you have an int value "intValue" and you want to set a specific bit at position "bitPosition", do something like:
intValue = intValue | (1 << bitPosition);
or shorter:
intValue |= 1 << bitPosition;
If you want to reset a bit (i.e, set it to zero), you can do this:
intValue &= ~(1 << bitPosition);
(The operator ~ reverses each bit in a value, thus ~(1 << bitPosition) will result in an int where every bit is 1 except the bit at the given bitPosition.)
To set everything to 0, AND the value with 0x00000000:
int startValue = initialValue & 0x00000000;
//Or much easier :)
int startValue = 0;
To then set the bit, you have to determine what number has just that bit set and OR it. For example, to set the last bit:
int finalValue = startValue | 0x00000001;
As #Magus points out, to unset a bit you do the exact opposite:
int finalValue = startValue & 0xFFFFFFFE;
//Or
int finalValue = startValue & ~(0x00000001);
The ~ operatior is bitwise not which flips every bit.
so, this?
enum ConditionEnum
{
Aaa = 0,
Bbb = 1,
Ccc = 2,
}
static void SetBit(ref int bitFlag, ConditionEnum condition, bool bitValue)
{
int mask = 1 << (int)condition;
if (bitValue)
bitFlag |= mask;
else
bitFlag &= ~mask;
}
Just provide a value, bit value and position. Note that you might be able to modify this to work for other types.
public static void SetBit(ref int value, bool bitval, int bitpos)
{
if (!bitval) value&=~(1<<bitpos); else value|=1<<bitpos;
}
I'm trying to debug some bit shifting operations and I need to visualize the bits as they exist before and after a Bit-Shifting operation.
I read from this answer that I may need to handle backfill from the shifting, but I'm not sure what that means.
I think that by asking this question (how do I print the bits in a int) I can figure out what the backfill is, and perhaps some other questions I have.
Here is my sample code so far.
static string GetBits(int num)
{
StringBuilder sb = new StringBuilder();
uint bits = (uint)num;
while (bits!=0)
{
bits >>= 1;
isBitSet = // somehow do an | operation on the first bit.
// I'm unsure if it's possible to handle different data types here
// or if unsafe code and a PTR is needed
if (isBitSet)
sb.Append("1");
else
sb.Append("0");
}
}
Convert.ToString(56,2).PadLeft(8,'0') returns "00111000"
This is for a byte, works for int also, just increase the numbers
To test if the last bit is set you could use:
isBitSet = ((bits & 1) == 1);
But you should do so before shifting right (not after), otherwise you's missing the first bit:
isBitSet = ((bits & 1) == 1);
bits = bits >> 1;
But a better option would be to use the static methods of the BitConverter class to get the actual bytes used to represent the number in memory into a byte array. The advantage (or disadvantage depending on your needs) of this method is that this reflects the endianness of the machine running the code.
byte[] bytes = BitConverter.GetBytes(num);
int bitPos = 0;
while(bitPos < 8 * bytes.Length)
{
int byteIndex = bitPos / 8;
int offset = bitPos % 8;
bool isSet = (bytes[byteIndex] & (1 << offset)) != 0;
// isSet = [True] if the bit at bitPos is set, false otherwise
bitPos++;
}
I know that the following is true
int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010
But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with.
Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop.
If you know the size of type, you could do something like:
uint i = 17;
uint j = i << 1 | i >> 31;
... which would perform a circular shift of a 32 bit value.
As a generalization to circular shift left n bits, on a b bit variable:
/*some unsigned numeric type*/ input = 17;
var result = input << n | input >> (b - n);
#The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this here. I also changed the example to use a uint.
One year ago I've to implement MD4 for my undergraduate thesis. Here it is my implementation of circular bit shift using a UInt32.
private UInt32 RotateLeft(UInt32 x, Byte n)
{
return UInt32((x << n) | (x >> (32 - n)));
}
Sincce .NET Core 3.0 and up there's BitOperations.RotateLeft() and BitOperations.RotateRight() so you can just use something like
BitOperations.RotateRight(12, 3);
BitOperations.RotateLeft(34L, 5);
In previous versions you can use BitRotator.RotateLeft() and BitRotator.RotateRight() in Microsoft.VisualStudio.Utilities
Just as reference on how to do it, these two functions work perfectly for rotating the bits of 1/2word:
static public uint ShiftRight(uint z_value, int z_shift)
{
return ((z_value >> z_shift) | (z_value << (16 - z_shift))) & 0x0000FFFF;
}
static public uint ShiftLeft(uint z_value, int z_shift)
{
return ((z_value << z_shift) | (z_value >> (16 - z_shift))) & 0x0000FFFF;
}
It would be easy to extend it for any given size.
The extension methods for rotating bits of a uint (32 bits):
public static uint ROR(this uint x, int nbitsShift)
=> (x >> nbitsShift) | (x << (32 - nbitsShift));
public static uint ROL(this uint x, int nbitsShift)
=> (x << nbitsShift) | (x >> (32 - nbitsShift));