This question already has answers here:
How to work with the bits in a byte
(4 answers)
Closed 3 years ago.
I encountered this problem on a task given to me.
Here's the situation:
If the user clicks on "Vat First" then the value is 0.
Else, the value is 1.
Then, in this Textbox,
The range of the value permitted is 0 to 15.
Then the example values are saved like this:
"01" = since it's vat first and 1mm Z-axis Up height.
"11" = Platform First, 1mm Z-axis up
"015" = vat first, 15mm
"115" = platform first, 15mm
The reason why it is saved like this because it is the file protocol given to me, and I can't do anything about it. It says there that the value is "Platform Moving order and Z Axis Up height" in 1 byte value.
My problem now is reading the result afterwards for reloading it to the application. How do I know if it just uses 3 or 2 digits since the return of int disregards the 0 in the beginning. "015" = "15" so my application might treat it as Platform First, 5 mm rather than Vat first, 15mm.
Edit: So I just realized thanks to #BenVoigt, that it is saved into a byte and it has 8 bits. According to the protocol given to me, the first 4-bits is the moving order (0 or 1) and the rest is for the Z-Axis Up Height (0-15). For the real question, how do I separate the byte into 4 bits each and get the value?
the first 4-bits is the moving order (0 or 1) and the rest is for the Z-Axis Up Height (0-15).
This is a straightforward bit-shifting task.
Order = Combined >> 4;
Height = Combined & 0x0F;
And saving:
Combined = (Order << 4) | Height;
The << and >> are the bitshift operators.
Can’t you just make both results strings and just append them together for your result? It seems that the integer type is your issue.
Related
I'm doing some entry level programming challenges at codefights.com and I came across the following question. The link is to a blog that has the answer, but it includes the question in it as well. If only it had an explanation...
https://codefightssolver.wordpress.com/2016/10/19/swap-adjacent-bits/
My concern is with the line of code (it is the only line of code) below.
return (((n & 0x2AAAAAAA) >> 1) | ((n & 0x15555555) << 1)) ;
Specifically, I'm struggling to find some decent info on how the "0x2AAAAAAA" and "0x15555555" work, so I have a few dumb questions. I know they represent binary values of 10101010... and 01010101... respectively.
1. I've messed around some and found out that the number of 5s and As corresponds loosely and as far as I can tell to bit size, but how?
2. Why As? Why 5s?
3. Why the 2 and the 1 before the As and 5s?
4. Anything else I should know about this? Does anyone know a cool blog post or website that explains some of this in more detail?
0x2AAAAAAA is 00101010101010101010101010101010 in 32 bits binary,
0x15555555 is 00010101010101010101010101010101 in 32 bits binary.
Note that the problem specifies Constraints: 0 ≤ n < 2^30. For this reason the highest two bits can be 00.
The two hex numbers have been "built" starting from their binary representation, that has a particular property (that we will see in the next paragraph).
Now... We can say that, given the constraint, x & 0x2AAAAAAA will return the even bits of x (if we count the bits as first, second, third... the second bit is even), while x & 0x15555555 will return the odd bits of x. By using << 1 and >> 1 you move them of one step. By using | (or) you re-merge them.
0x2AAAAAAA is used to get 30 bits, which is the constraint.
Constraints:
0 ≤ n < 2^30.
0x15555555 also represent 30 bits with bits opposite of other number.
I would start with binary number (101010101010101010101010101010) in the calculator and select hex using programmer calculator to show the number in hex.
you can also use 0b101010101010101010101010101010 too, if you like, depending on language.
I have a 32 bit integer which I fill with data by mapping the individual bits to various types of data.
For instance one section is used for oxygen level. It's a value from 0 to 128, so I use 7 bits for that.
Another section is used for the rotation of the object. Rotation is always either 0, 90, 180 or 270 degrees around the three axis x, y and z. Each angle is indexed with the values 0, 1, 2 and 3, so I only need 6 bits. Rotation is stored as 010101 for a rotation of 90 deg around x, y and z, or 100000 for a rotation of 180 deg around x.
Some of the sections are stored as integer values, like with oxygen level, but cast to enums when I need to use them.
Each of the sections are laid out next to each other in the data integer, filling the bits from right to left.
Type : ... | Oxygen | Rotation |
--------------------------
Bits: ... | 0000000 | 000000 |
--------------------------
Position: ... | 19-25 | 26-31 |
--------------------------
The problem
I would like to compare two integers and see what's changed.
When the oxygen level of one int is 16, and the other is 20, the difference is an increase of 4 units. When one rotation is 0 on all axis, and an other is 90 around x, the difference is a rotation around x of 90 deg.
I have extension methods on the data object that allows me to get the oxygen level as an int value, and the rotation as a quaternion. When using these on the delta data object, I would like to get the value 4 for oxygen level, and a quaternion for the rotation 90 deg around x.
Question
What's the most efficient way to get the difference in value of two integers?
Possible approaches
I've thought about a couple of different ways to approach this.
Integer comparing
Since the data is an integer, I tried to simply subtract one from the other. I started with an int with a value of 0 and set the bits for oxygen level to 16. I created a new int, set its oxygen level to 20, and subtracted the first from the last, and the oxygen level of the delta was 4. But as I added rotation and other data to the integers, the result after the subtraction changed the resulting oxygen level and rotation.
I need to verify that all my extension methods are working as intended. All unit tests succeeds, but the tests might not be good enough.
Bitwise comparing
Another approach was to compare each bit separately throughout the entire integer, using the various bitwise operators. I used an int with the rotation bits set to 90 deg around x (bits 01). Another int had the x rotation set to 180 deg (bits 10). The delta value I was looking for is 90 deg (bits 01), but I couldn't find any suitable operators to produce that result.
This test led me to believe that I can't compare bits separately. In the case of the rotation indexes, I need to look at a pair of bits as a single value.
BitArray
I read the documentation for .net's BitArray, but couldn't immediately see using that would make any difference.
Compare each section
Comparing each bit section would produce the result I'm looking for. The rotation bits would be converted to a quaternion before calculating the difference, and then converted back to bits before setting them in the data integer.
This is the approach I was hoping to find an alternative to. I didn't want the comparer to know the structure of the data, and I was hoping to find a more efficient solution.
Edit
I see now, after reading the comments and doing more testing, that it would be more beneficial for my case to get only the new value of a bit section, and not how much they changed. Any section that remains unchanged should be zeroed out. As far as I can see, my only option is to compare the data sectionwise.
Edit again
I'm not sure which answer to pick as the correct one. I don't think my question was specific enough, and am sorry for that.
The method given by #harold works when comparing bit by bit, and is independent of the data structure.
The answer by #Pikoh compares section by section, and can be made dynamic so that the method won't need to know about the data structure.
I am not exactly sure what you wanted, but it is certainly possible to compute the modular difference for all fields, using typical SWAR techniques:
z = ((x | H) - (y &~H)) ^ ((x ^~y) & H)
This is the general formula for SWAP subtraction. For 2-bit fields, H = 0xAAAAAAAA.
Since there are only two bits and SWAR usually treats the top bit differently (to prevent leaking into the next field), the bits are effectively totally separate.
With the new requirements it is also not necessary to do ugly splitting of the fields, for example: (not tested)
m = x ^ y;
m = (m | (m >> 1)) & 0x55555555;
m *= 3;
z = y & m; // maybe
The idea here is that a xor will produce a 1 somewhere in a field iff it has changed, then OR all bits of the field and put it in the lowest bit of the field, the multiplication by 3 broadcasts it to all bits of the field. & with the new value to get changed fields and zeroes elsewhere, but that means you cannot distinguish between "changed to 0" and "unchanged". Using m you can still distinguish them.
Let's see if something like this helps you:
int data1 = Convert.ToInt32("00000000000000000000000000011100", 2); //sample data
int data2 = Convert.ToInt32("00000000000000000000000000101000", 2);
int xrotationposition = 26; //start positions of data
int yrotationposition = 28;
string xrotationmask = new string('0', xrotationposition) + "11" +
new string('0',30 - xrotationposition); //mask to extract the data
string yrotationmask = new string('0', yrotationposition) + "11" +
new string('0', 30 - yrotationposition);
int xrotation1 = data1 & Convert.ToInt32(xrotationmask, 2); //bit AND
int xrotation2 = data2 & Convert.ToInt32(xrotationmask, 2);
int yrotation1 = data1 & Convert.ToInt32(yrotationmask, 2);
int yrotation2 = data2 & Convert.ToInt32(yrotationmask, 2);
xrotation1 = (xrotation1 >> 30 - xrotationposition); //shift the bits
to the lowest part of byte
xrotation2 = (xrotation2 >> 30 - xrotationposition);
yrotation1 = (yrotation1 >> 30 - yrotationposition);
yrotation2 = (yrotation2 >> 30 - yrotationposition);
At the end of this execution, you'll get xrotation1=1, xrotation2=2,yrotation1=3 and yrotation2=2, that seems easy values to compare.
Hope this helps
I'm trying to do the following:
10^((77-109)/32) = 0,1
In C#:
MessageBox.Show((Math.Pow((((77-109)/ 32)), 10)).ToString());
Output:
1
What is going on? How can I get the right answer?
You're using all integers operands which leads C# to use integer arithmetics;
(88-109)/32 = (rounded down to) 0, and 0^10 = 0 (which is what your code line will display, not 1)
The correct line to get the result you want at the top of your question is;
MessageBox.Show((Math.Pow(10.0, (77.0 - 109.0) / 32.0)).ToString());
Which, correctly, will show 0.1. Note the change to decimal numbers instead of integers, and the swap of the (erroneous) x^10 to 10^x.
You've swapped the parameters in Math.pow; your code is raising (88-109)/32 to the power of 10, and as a result, you are getting unexpected results. Swapping the parameters (and correcting 88 to 77) will give you the expected result of 0.1, as it then will evaluate 10^-1.
MessageBox.Show((Math.Pow(10, (77 - 109) / 32)).ToString());
We are rewriting some applications previously developed in Visual FoxPro and redeveloping them using .Net ( using C# )
Here is our scenario:
Our application uses smartcards. We read in data from a smartcard which has a name and number. The name comes back ok in readable text but the number, in this case '900' comes back as a 2 byte character representation (131 & 132) and look like this - ƒ„
Those 2 special characters can be seen in the extended Ascii table.. now as you can see the 2 bytes are 131 and 132 and can vary as there is no single standard extended ascii table ( as far as I can tell reading some of the posts on here )
So... the smart card was previously written to using the BINTOC function in VFP and therefore the 900 was written to the card as ƒ„. And within foxpro those 2 special characters can be converted back into integer format using CTOBIN function.. another built in function in FoxPro..
So ( finally getting to the point ) - So far we have been unable to convert those 2 special characters back to an int ( 900 ) and we are wondering if this is possible in .NET to read the character representation of an integer back to an actual integer.
Or is there a way to rewrite the logic of those 2 VFP functions in C#?
UPDATE:
After some fiddling we realise that to get 900 into 2bytes we need to convert 900 into a 16bit Binary Value, then we need to convert that 16 bit binary value into a decimal value.
So as above we are receiving back 131 and 132 and their corresponding binary values as being 10000011 ( decimal value 131 ) and 10000100 ( decimal value 132 ).
When we concatenate these 2 values to '1000001110000100' it gives the decimal value 33668 however if we removed the leading 1 and transform '000001110000100' to decimal it gives the correct value of 900...
Not too sure why this is though...
Any help would be appreciated.
It looks like VFP is storing your value as a signed 16 bit (short) integer. It seems to have a strange changeover point to me for the negative numbers but it adds 128 to 8 bit numbers and adds 32768 to 16 bit numbers.
So converting your 16 bit numbers from the string should be as easy as reading it as a 16 bit integer and then taking 32768 away from it. If you have to do this manually then the first number has to be multiplied by 256 and then add the second number to get the stored value. Then take 32768 away from this number to get your value.
Examples:
131 * 256 = 33536
33536 + 132 = 33668
33668 - 32768 = 900
You could try using the C# conversions as per http://msdn.microsoft.com/en-us/library/ms131059.aspx and http://msdn.microsoft.com/en-us/library/tw38dw27.aspx to do at least some of the work for you but if not it shouldn't be too hard to code the above manually.
It's a few years late, but here's a working example.
public ulong CharToBin(byte[] s)
{
if (s == null || s.Length < 1 || s.Length > 8)
return 0ul;
var v = s.Select(c => (ulong)c).ToArray();
var result = 0ul;
var multiplier = 1ul;
for (var i = 0; i < v.Length; i++)
{
if (i > 0)
multiplier *= 256ul;
result += v[i] * multiplier;
}
return result;
}
This is a VFP 8 and earlier equivalent for CTOBIN, which covers your scenario. You should be able to write your own BINTOC based on the code above. VFP 9 added support for multiple options like non-reversed binary data, currency and double data types, and signed values. This sample only covers reversed unsigned binary like older VFP supported.
Some notes:
The code supports 1, 2, 4, and 8-byte values, which covers all
unsigned numeric values up to System.UInt64.
Before casting the
result down to your expected numeric type, you should verify the
ceiling. For example, if you need an Int32, then check the result
against Int32.MaxValue before you perform the cast.
The sample avoids the complexity of string encoding by accepting a
byte array. You would need to understand which encoding was used to
read the string, then apply that same encoding to get the byte array
before calling this function. In the VFP world, this is frequently
Encoding.ASCII, but it depends on the application.
Part of my application data contains a set of 9 ternary (base-3) "bits". To keep the data compact for the database, I would like to store that data as a single short. Since 3^9 < 2^15 I can represent any possible 9 digit base-3 number as a short.
My current method is to work with it as a string of length 9. I can read or set any digit by index, and it is nice and easy. To convert it to a short though, I am currently converting to base 10 by hand (using a shift-add loop) and then using Int16.Parse to convert it back to a binary short. To convert a stored value back to the base 3 string, I run the process in reverse. All of this takes time, and I would like to optimize it if at all possible.
What I would like to do is always store the value as a short, and read and set ternary bits in place. Ideally, I would have functions to get and set individual digits from the binary in place.
I have tried playing with some bit shifts and mod functions, but havn't quite come up with the right way to do this. I'm not even sure if it is even possible without going through the full conversion.
Can anyone give me any bitwise arithmetic magic that can help out with this?
public class Base3Handler
{
private static int[] idx = {1, 3, 9, 27, 81, 243, 729, 729*3, 729*9, 729*81};
public static byte ReadBase3Bit(short n, byte position)
{
if ((position > 8) || (position < 0))
throw new Exception("Out of range...");
return (byte)((n%idx[position + 1])/idx[position]);
}
public static short WriteBase3Bit(short n, byte position, byte newBit)
{
byte oldBit = ReadBase3Bit(n, position);
return (short) (n + (newBit - oldBit)*idx[position]);
}
}
These are small numbers. Store them as you wish, efficiently in memory, but then use a table lookup to convert from one form to another as needed.
You can't do bit operations on ternary values. You need to use multiply, divide and modulo to extract and combine values.
To use bit operations you need to limit the packing to 8 ternaries per short (i.e. 2 bits each)