We are working on modding an old 16Bit era video game cartridge. We are hoping to inject some our own Sprites into the game to dip our toes in the water.
To do so, we are developing an app to both display the Sprites and convert new ones to the Hex (to make it easier to inject.)
The game stores individual pixels as 2 Digit Hexidecimal Values (0x0~0xFFFF). The game uses bitwise shifts to establish the individual Red, Green, and Blue colors. There's some old documentation we had to fall back from the Sprite Resources community to confirm this. This confirmed use of two masks.
We have the display function working perfectly. The function receives the HEX then returns an ARRAY with the 3 values: R, G, B.
In the group, we do not have anyone particularly good working with bitwise shifts. We are looking for help turning the 3 "int" colors back into it's original single 2 Digit Hex.
ANSWERED!! THANKS
First, are you sure you want to use ~ in your calculation here:
colorRGB0R = ~(((HexPixelValue >> 11) & PixelMask1) << 3);
colorRGB0G = ~(((HexPixelValue >> 5) & PixelMask2) << 2);
colorRGB0B = ~((HexPixelValue & PixelMask1) << 3);
Because the math appears fine except for that? Maybe the commented part does something with the values but I'm not quite sure why you're inverting them. In any case...
Basically, you are working with a 565 16 bit color then. Rather than that bitmask, it is a lot easier to understand if you write the bit layout of the 16 bit value like this: rrrrrggg gggbbbbb as it visualizes which bits you want to set with what values.
Meaning that red and blue are 5 bit values (0-31) and green is a 6 bit value (0-63). However, since color values are meant to be in the range of 0-255, after extracting the bits, you have to multiply them to get the range. The multiplying here is done by bit shifting as well.
To reconstruct the 16 bit value, you can do something like this:
int ToHex(int red, int green, int blue)
{
if (red < 0 || red >= 256)
throw new ArgumentOutOfRangeException(nameof(red));
if (green < 0 || green >= 256)
throw new ArgumentOutOfRangeException(nameof(green));
if (blue < 0 || blue >= 256)
throw new ArgumentOutOfRangeException(nameof(blue));
// red & 0xF8 cuts off the bottom 3 bits to be save
// green & 0xFC cuts off the bottom 2 bits
// blue needs to be shifted to the right anyway, so we use that to cut off 3 bits
return ((red & 0xF8) << 8) |
((green & 0xFC) << 3) |
(blue >> 3);
}
Related
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.
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've read this post and in the part 2) Use Layers of Leosori's answer he use bit shift to get the bit mask. I wanted to have an explanation of how bit shift work (I didn't found my answer on the manual either).
In the example it is shown how to cast only on layer 8:
int layerMask = 1 << 8;
// This would cast rays only against colliders in layer 8.
So, how can I use bit shift to get the bit mask of layers 9 and 10 at the same time?
In my project I have some ray casts on my player to be able to know if he sees some specific objects (layer 10). If the objects are behind a wall (layer 9) the player shouldn't be able to see it. I would like to raycast on both layers and test if the hit.collider.gameObject.tag is "seekObjects". I know there are other solutions to do this but I would like to understand how bit shift works.
Manipulating individual bits is mainly done using the &, |, ~ and <</>> operators.
Example (with bytes):
// single value
byte a = 1; // 00000001
// shift "a" 3 bits left
byte b = a << 3; // 00001000
// combine a and b with bitwise or (|)
byte c = a | b; // 00001001
So in your case, to get bit 9 and bit 10 set, do:
int layerMask = ( 1 << 9 ) | ( 1 << 10 );
Notice that we're using | and not ||, which is logical or.
I want to know if one needs to mask a number before retrieving the value stored at a certain byte when doing bit shifting.
Take, for example, this code:
short b1 = 1;
short b2 = 2;
short b0 = (short)((b1 << 8) | b2); //store two values in one variable
Console.WriteLine(b0); //b1 and b2 combined
Console.WriteLine((b0 & (255 << 8)) >> 8); //gets the value of b1
As far as I am concerned, doing a right shift drops all bits that are less than the number of bits you've shifted. Therefore, right shifting b0 by 8 bits will drop the 8 bits of b2, leaving just b1.
Console.WriteLine(b0 >> 8); //this also gets b1!!
I want to find out, is there any need to mask b0 with 255 << 8 before shifting to get the value of b1?
NB:
The only need I can think of for masking before retrieving a value is if there is something else stored at a higher byte, such as trying to get back the value of b2, in which this code would be used:
Console.WriteLine(b0 & 255); //gets the value of b2
I want to find out, is there any need to mask b0 with 255 << 8 before shifting to get the value of b1?
No, there's no need. So the compiler will omit the masking. Some people think it makes the code easier to understand or protects them against some imagined failure scenario. It's completely harmless.
I just started learning about Kinect through some quick start videos and was trying out the code to work with depth data.
However, I am not able to understand how the distance is being calculated using bit-shifting and various other formulas that are being employed to calculate other stuff too while working with this depth data.
http://channel9.msdn.com/Series/KinectSDKQuickstarts/Working-with-Depth-Data
Are these the particulars which are Kinect-specifics explained in the documentation etc.? Any help would be appreciated.
Thanks
Pixel depth
When you don't have the kinect set up to detect players, it is a simply array of bytes, with two bytes representing a single depth measurement.
So, just like in a 16 bit color image, each sixteen bits represent a depth rather than a color.
If the array were for a hypothetical 2x2 pixel depth image, you might see: [0x12 0x34 0x56 0x78 0x91 0x23 0x45 0x67] which would represent the following four pixels:
AB
CD
A = 0x34 << 8 + 0x12
B = 0x78 << 8 + 0x56
C = 0x23 << 8 + 0x91
D = 0x67 << 8 + 0x45
The << 8 simply moves that byte into the upper 8 bits of a 16 bit number. It's the same as multiplying it by 256. The whole 16 bit numbers become 0x3412, 0x7856, 0x2391, 0x6745. You could instead do A = 0x34 * 256 + 0x12. In simpler terms, it's like saying I have 329 items and 456 thousands of items. If I have that total of items, I can multiply the 456 by 1,000, and add it to the 329 to get the total number of items. The kinect has broken the whole number up into two pieces, and you simply have to add them together. I could "shift" the 456 over to the left by 3 zero digits, which is the same as multiplying by 1,000. It would then be 456000. So the shift and the multiplication are the same thing for whole amounts of 10. In computers, whole amounts of 2 are the same - 8 bits is 256, so multiplying by 256 is the same as shifting left by 8.
And that would be your four pixel depth image - each resulting 16 bit number represents the depth at that pixel.
Player depth
When you select to show player data it becomes a little more interesting. The bottom three bits of the whole 16 bit number tell you the player that number is part of.
To simplify things, ignore the complicated method they use to get the remaining 13 bits of depth data, and just do the above, and steal the lower three bits:
A = 0x34 << 8 + 0x12
B = 0x78 << 8 + 0x56
C = 0x23 << 8 + 0x91
D = 0x67 << 8 + 0x45
Ap = A % 8
Bp = B % 8
Cp = C % 8
Dp = D % 8
A = A / 8
B = B / 8
C = C / 8
D = D / 8
Now the pixel A has player Ap and depth A. The % gets the remainder of the division - so take A, divide it by 8, and the remainder is the player number. The result of the division is the depth, the remainder is the player, so A now contains the depth since we got rid of the player by A=A/8.
If you don't need player support, at least at the beginning of your development, skip this and just use the first method. If you do need player support, though, this is one of many ways to get it. There are faster methods, but the compiler usually turns the above division and remainder (modulus) operations into more efficient bitwise logic operations so you don't need to worry about it, generally.