sql stored procedures and bitwise operators - mysql

I have a categories table:
id;description;special
----------------------
1;Spares;TRUE
2;Accessories;TRUE
4;Consumables;TRUE
8;Services;TRUE
11;Printer;FALSE
12;Monitor;FALSE
13;Other;FALSE
The special field designates special categories that have fixed ids and cannot be deleted nor modified. I've assigned bitwise OR-able ids to those.
Then I have items, each item belongs to a category (with a 1:n relationship).
Now I'd like to write a stored procedure that takes an input parameter containing an OR-ed combination of ids:
1 I want spare parts
2 I want accessories
4 I want consumables
**5 I want consumables AND spare parts**
etc
If the parameter is NULL, then I want every item regardless of its category.
This is quite easy, say the parameter is called _or_category, then the WHERE clause could be something like:
SELECT
*
FROM
items I
JOIN
categories C ON (C.id = I.category)
WHERE
(_or_category IS NULL) OR (C.special = TRUE AND C.id | _or_categoria = _or_categoria)
;
First problem:
*edit: sorry this is not a problem, since I have C.special=TRUE in the WHERE clause.*
category 12 could be "seen" as id=8 OR 4, thus if I want to select only the consumables, I would get also the monitors!
Second problem:
I don't know how to specify when I want all the items which are NOT a service (cat: 8).

Second problem: I don't know how to
specify when I want all the items
which are NOT a service (cat: 8)
If I understand your question I think you're looking for the bitwise Invert bits ~
for example
C.special = TRUE AND (~C.ID | or_categoria = _or_categoria)

You need
0x01 - Spares
0x02 - Accessories
0x04 - Consumables
0x08 - Services
0x10 - Printer
0x20 - Monitor
0x40 - Other
And all things not services = 0x7F & ~0x08
Edit: If you only want the first 4 things to be flags it is not much different. The first 4 bits are reserved exclusively for your bit comparisons. So you cannot have any additional ids that would require a value in the first 4 bits (from the right)...
0x01 - Spares
0x02 - Accessories
0x04 - Consumables
0x08 - Services
0x10 - Printer
0x20 - Monitor
0x30 - Other
And again, Ax(~Sx) = 0x3F & ~0x08

Related

Binary numbers addition

I have just started doing some binary number exercices to prepare for a class that i will start next month and i got the hang of all the conversion from decimal to binary and viceverca But now with the two letters 'a ' ' b' in this exercise i am not sure how can i apply that knowledge to add the bits with the following exercise
Given two Binary numbers a = (a7a6 ... a0) and b = (b7b6 ... b0).There is a clculator that can add 4-bit binary numbers.How many bits will be used to represent the result of a 4-bit addition? Why?
We would like to use our calculator to calculate a + b. For this we can put as many as eight bits (4 bits of the first and 4 bits of the second number) of our choice in the calculator and continue to use the result bit by bit
How many additions does our calculator have to carry out for the addition of a and b at most? How many bits is the result maximum long?
How many additions does the calculator have to perform at least For the result to be correct for all possible inputs a and b?
The number of bits needed to represent a 4-bit binary addition is 5. This is because there could be a carry-over bit that pushes the result to 5 bits.
For example 1111 + 0010 = 10010.
This can be done the same way as adding decimal numbers. From right to left just add the numbers of the same significance. If the two bits are 1+1, the result is 10 so that place becomes a zero and the 1 carries over to the next pair of bits, just like decimal addition.
With regard to the min/max number of step, these seems more like an algorithm specific question. Look up some different binary addition algorithms, like ripple-carry for instance, and it should give you a better idea of what is meant by the question.

How to get OBD2 Fuel Level reading from Wagon R 2010 model

I want to measure current fuel level inside my car's fuel tank using OBD2 bluetooth/USB adapter.
When i try to query that PID i got following data as "NO DATA" while at the same time i can check other PIDS like RPM and all data comes fine.
I have small python program which reads its but i am unable to get it.
import serial
#ser = serial.Serial('COM12',38400,timeout=1)
#ser.write("01 2F \r")
#speed_hex = ser.readline().split(' ')
#print speed_hex
#convert hex to decprint ("SpeedHex",speed_hex)
#speed = float(int('0x'+speed_hex[3],0))
#print ('Speed',speed,'Km/h')
ser1 = serial.Serial("COM12",38400,timeout=1)
#ser1.write("ATZ \r")
#ser1.write("ATE0 \r")
#ser1.write("ATL0 \r")
#ser1.write("ATH1 \r")
#ser1.write("ATSP 5 \r")
ser1.write("01 0C \r")
fuel_hex= ser1.readline()
print fuel_hex
#convert to hex to decprint ("FuelHex",fuel_hex)
#fuel = float(int('0x'+fuel_hex[3],0))
#print ("Fuel in Per",fuel)
Can any one suggest here how to get fuel level which is their inside in car at this current time. As i can see in my panel with bar sign.
In order to get all the available PIDs in a vehicle, you have to request the following PIDs at first exactly like you ask the rpm of the vehicle:
0x00, 0x20, 0x40, ....0x80 and so on.
For instance when you request PID 0x00 the ECU will return you 4 bytes which means if it supports PIDs from 0x01 - 0x20. Each byte has 8 bits in total of 32 bits which is exactly from PID 0x01 to PID 0x20. Now it is time to parse the data. If each bit is 1 it means the ECU will support and 0 no support. It is your duty to do some bitwise operations to translate these bits:
Also you can look out this Wikipedia link which shows in graphics!
byte 1 bit 1 : availability of PID 0x01
byte 1 bit 2 : availability of PID 0x02
byte 1 bit 3 : availability of PID ox03
....
byte 4 bit 7 : availability of PID 0x1F
byte 4 bit 8 : availability of PID 0x20 --> Here the ECU tells you if support any PIDs in next 32 PIDs. If it is 0, you do not need to check anymore!
After parsing and gathering all the supported PIDs, then you can have a roadmap to calculate or check each PIDs you want. Do not forget many of conversion rates a formulas in wikipedia is wrong due to the complexity of calculations. You have to read the ISO 15031 part 5 and do NOT forget ECU only gives you the emissions-related diagnostics and not all the data.

represent bitmask value in JSON object

What is the best way to represent bit-mask values in JSON object?
For example:
we want to know what ingredients user want in his fruit salad
Orange = 0x01
Apple = 0x02
Banana = 0x04
Grapes = 0x08
How would one represent the selected options in a JSON Object, obviously we can use integer value (i.e. 3 is for Orange and Apple) but it is not quite readable.
Is there are a better way?!
Researching a bit on this topic uncovered the following case study:
https://www.smartsheet.com/blog/smartsheet-api-formatting
It's not exactly the same problem, but it was good for extrapolating some solutions here:
Send a list of integers, from a predefined lookup table: e.g. [1, 3] (compromise between space and parsing)
Send the actual bit mask value (harder to parse, takes the least space)
Send a list of strings: e.g. [Orange, Banana] (easy to read, takes most space)
If space is not a constraint, I think the last options is the best.

Is it possible to program in binary?

Is it possible to program in binary?
A friend of mine told me he knows someone who can program in binary. I've never heard of someone programming in binary and a few quick Google searches didn't return anything useful. So I figured I'd turn to the SO community. Does anyone have any info on programming in binary and if possible maybe a quick Hello World example.
Of course. It's more commonly called machine code. It's basically assembly language without the mnemonic devices. Someone who knows assembly very well could program in machine code with additional effort, referring to opcode listings (e.g. x86) as needed.
Would I do it? No. Even assembly is only useful in rare circumstances, and there's no reason (beside demonstrating your skills) to reject the assembler's help.
Since you asked about hello world, you should check out this article. He shows how he wrote, then optimized, an x86 ELF program to output it. It was originally written in nasm then modified in a hex editor.
It's very much possible to memorize machine code equivalent of assembly instructions. Actually, when writing code in assembly language, one often happens to see hex code through machine code monitors, disassemblers, assembly listings, etc. As a result, over time some instructions can be memorized in their hex form without any extra effort.
In the picture an 6502 ROM monitor is seen, where hex code and assembly mnemonics are shown side by side.
Second skill you're going to need is to transform hex code into binary which is quite easy with a trick I'll explain in a bit.
Think of the following instructions:
OPCODE HEX
LDA #imm 0xA9 imm
STA adr 0x85 adr
STA (adr),Y 0x91 adr
LDY #imm 0xA0 imm
With above opcodes memorized only, we can write the following machine code using only pen and paper:
0xA9 0x00
0x85 0x01
0xA9 0x02
0x85 0x02
0xA0 0x00
0xA9 0x01
0x91 0x01
Actually the above is the following assembly code in mnemonic form:
LDA #00
STA $01
LDA #02
STA $02
LDY #00
LDA #01
STA ($01), Y
The above code puts a white pixel at the top-left corner of screen in 6502asm.com assembler/emulator, go ahead and try it out!
Now the trick for converting hexadecimals into binary and vice versa is to work it out only for nibbles (4-bit values).
First, remember how to convert binary into decimal. Every time you see 1, multiply that by its binary power. E.g. 101 would be 4 + 0 + 1 = 5. It can be visualized like this:
1 1 1 1 --> binary points
| | | |
v v v v
8 + 4 + 2 + 1
| | | +---> 2^0 * 1 Ex: 13 is 8 + 4 + 0 + 1
| | +-------> 2^1 * 1 1 1 0 1 -> 1101 (0xD)
| +-----------> 2^2 * 1 Ex: 7 is 0 + 4 + 2 + 1
+---------------> 2^3 * 1 0 1 1 1 -> 0111 (0x7)
With this in mind, and well practiced, the following should be possible:
LDA #00 -> 0xA9 0x00 -> 1010 1001 0000 0000
STA $01 -> 0x85 0x01 -> 1000 0101 0000 0001
LDA #02 -> 0xA9 0x02 -> 1010 1001 0000 0010
STA $02 -> 0x85 0x02 -> 1000 0101 0000 0010
LDY #00 -> 0xA0 0x00 -> 1010 0000 0000 0000
LDA #01 -> 0xA9 0x01 -> 1010 1001 0000 0001
STA ($01),Y -> 0x91 0x01 -> 1001 0001 0000 0001
With some retro computing spirit, motivation and fun, we could actually have written the entire code in binary without writing down the intermediate steps.
On a related note, Paul Allen coded a boot loader for Altair 8800 with pen and paper on an airplane, and possibly had to translate it to binary also with pen and paper: https://www.youtube.com/watch?v=2wEyqJnhec8
There isn't much call for it any more, but it has been done. There was a time when code could be entered into a system in binary from the front console. It was error prone.
I used to have a very short uudecoe program encoded in ASCII which could be prefixed to a UUEncoded file. The resulting file would be self-extracting and could be emailed around. I would expect the machine code was hand done. I can't find it, and don't have a use for it even if I could.
Well of course you can write the binary for the machine code and then enter the machine code via your hex key pad into your computer. I have put together a computer based on the TMS1100.
A simple program to display 5 on the hex LED would be 0001000 0000101 0000001 written in binary converted to machine code that would be 8 5 1 . This program would then run and display 5 on the LED.
You could follow this procedure for far more complex programs using the TMS1100 and I guess programming in binary.
Actually, I think this is very satisfying and rewarding if you are interested in mathematics and programming.
For the brave of heart: you can try getting a MikeOS floppy image and running the monitor.bin program. It allows you to enter hexadecimal opcodes by hand and execute them. For example (as stated on the docs), entering the following instructions:
BE0790 E8FD6F C3 4D00$ will produce a single M on the screen.
There are some esoteric programming languages. They are used as experiments, and are rather impractical, but one, called BrainF**k (yes, it is actually a real thing) uses eight different characters to modify byte values. Those kind of languages are about as close as you can get.

Real world use cases of bitwise operators [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
What are some real world use cases of the following bitwise operators?
AND
XOR
NOT
OR
Left/Right shift
Bit fields (flags)
They're the most efficient way of representing something whose state is defined by several "yes or no" properties. ACLs are a good example; if you have let's say 4 discrete permissions (read, write, execute, change policy), it's better to store this in 1 byte rather than waste 4. These can be mapped to enumeration types in many languages for added convenience.
Communication over ports/sockets
Always involves checksums, parity, stop bits, flow control algorithms, and so on, which usually depend on the logic values of individual bytes as opposed to numeric values, since the medium may only be capable of transmitting one bit at a time.
Compression, Encryption
Both of these are heavily dependent on bitwise algorithms. Look at the deflate algorithm for an example - everything is in bits, not bytes.
Finite State Machines
I'm speaking primarily of the kind embedded in some piece of hardware, although they can be found in software too. These are combinatorial in nature - they might literally be getting "compiled" down to a bunch of logic gates, so they have to be expressed as AND, OR, NOT, etc.
Graphics
There's hardly enough space here to get into every area where these operators are used in graphics programming. XOR (or ^) is particularly interesting here because applying the same input a second time will undo the first. Older GUIs used to rely on this for selection highlighting and other overlays, in order to eliminate the need for costly redraws. They're still useful in slow graphics protocols (i.e. remote desktop).
Those were just the first few examples I came up with - this is hardly an exhaustive list.
Is it odd?
(value & 0x1) > 0
Is it divisible by two (even)?
(value & 0x1) == 0
I've used bitwise operations in implementing a security model for a CMS. It had pages which could be accessed by users if they were in appropriate groups. A user could be in multiple groups, so we needed to check if there was an intersection between the users groups and the pages groups. So we assigned each group a unique power-of-2 identifier, e.g.:
Group A = 1 --> 00000001
Group B = 2 --> 00000010
Group C = 3 --> 00000100
We OR these values together, and store the value (as a single int) with the page. E.g. if a page could be accessed by groups A & B, we store the value 3 (which in binary is 00000011) as the pages access control. In much the same way, we store a value of ORed group identifiers with a user to represent which groups they are in.
So to check if a given user can access a given page, you just need to AND the values together and check if the value is non-zero. This is very fast as this check is implemented in a single instruction, no looping, no database round-trips.
Here's some common idioms dealing with flags stored as individual bits.
enum CDRIndicators {
Local = 1 << 0,
External = 1 << 1,
CallerIDMissing = 1 << 2,
Chargeable = 1 << 3
};
unsigned int flags = 0;
Set the Chargeable flag:
flags |= Chargeable;
Clear CallerIDMissing flag:
flags &= ~CallerIDMissing;
Test whether CallerIDMissing and Chargeable are set:
if((flags & (CallerIDMissing | Chargeable )) == (CallerIDMissing | Chargeable)) {
}
Low-level programming is a good example. You may, for instance, need to write a specific bit to a memory-mapped register to make some piece of hardware do what you want it to:
volatile uint32_t *register = (volatile uint32_t *)0x87000000;
uint32_t value;
uint32_t set_bit = 0x00010000;
uint32_t clear_bit = 0x00001000;
value = *register; // get current value from the register
value = value & ~clear_bit; // clear a bit
value = value | set_bit; // set a bit
*register = value; // write it back to the register
Also, htonl() and htons() are implemented using the & and | operators (on machines whose endianness(Byte order) doesn't match network order):
#define htons(a) ((((a) & 0xff00) >> 8) | \
(((a) & 0x00ff) << 8))
#define htonl(a) ((((a) & 0xff000000) >> 24) | \
(((a) & 0x00ff0000) >> 8) | \
(((a) & 0x0000ff00) << 8) | \
(((a) & 0x000000ff) << 24))
I use them to get RGB(A) values from packed colorvalues, for instance.
When I have a bunch of boolean flags, I like to store them all in an int.
I get them out using bitwise-AND. For example:
int flags;
if (flags & 0x10) {
// Turn this feature on.
}
if (flags & 0x08) {
// Turn a second feature on.
}
etc.
& = AND:
Mask out specific bits.
You are defining the specific bits which should be displayed
or not displayed. 0x0 & x will clear all bits in a byte while 0xFF will not change x.
0x0F will display the bits in the lower nibble.
Conversion:
To cast shorter variables into longer ones with bit identity it is necessary to adjust the bits because -1 in an int is 0xFFFFFFFF while -1 in a long is 0xFFFFFFFFFFFFFFFF. To preserve
the identity you apply a mask after conversion.
|=OR
Set bits. The bits will be set indepently if they are already set. Many datastructures (bitfields) have flags like IS_HSET = 0, IS_VSET = 1 which can be indepently set.
To set the flags, you apply IS_HSET | IS_VSET (In C and assembly this is very convenient to read)
^=XOR
Find bits which are the same or different.
~= NOT
Flip bits.
It can be shown that all possible local bit operations can be implemented by these operations.
So if you like you can implement an ADD instruction solely by bit operations.
Some wonderful hacks:
http://www.ugcs.caltech.edu/~wnoise/base2.html
http://www.jjj.de/bitwizardry/bitwizardrypage.html
Encryption is all bitwise operations.
You can use them as a quick and dirty way to hash data.
int a = 1230123;
int b = 1234555;
int c = 5865683;
int hash = a ^ b ^ c;
I just used bitwise-XOR (^) about three minutes ago to calculate a checksum for serial communication with a PLC...
This is an example to read colours from a bitmap image in byte format
byte imagePixel = 0xCCDDEE; /* Image in RRGGBB format R=Red, G=Green, B=Blue */
//To only have red
byte redColour = imagePixel & 0xFF0000; /*Bitmasking with AND operator */
//Now, we only want red colour
redColour = (redColour >> 24) & 0xFF; /* This now returns a red colour between 0x00 and 0xFF.
I hope this tiny examples helps....
In the abstracted world of today's modern language, not too many. File IO is an easy one that comes to mind, though that's exercising bitwise operations on something already implemented and is not implementing something that uses bitwise operations. Still, as an easy example, this code demonstrates removing the read-only attribute on a file (so that it can be used with a new FileStream specifying FileMode.Create) in c#:
//Hidden files posses some extra attibutes that make the FileStream throw an exception
//even with FileMode.Create (if exists -> overwrite) so delete it and don't worry about it!
if(File.Exists(targetName))
{
FileAttributes attributes = File.GetAttributes(targetName);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
File.SetAttributes(targetName, attributes & (~FileAttributes.ReadOnly));
File.Delete(targetName);
}
As far as custom implementations, here's a recent example:
I created a "message center" for sending secure messages from one installation of our distributed application to another. Basically, it's analogous to email, complete with Inbox, Outbox, Sent, etc, but it also has guaranteed delivery with read receipts, so there are additional subfolders beyond "inbox" and "sent." What this amounted to was a requirement for me to define generically what's "in the inbox" or what's "in the sent folder". Of the sent folder, I need to know what's read and what's unread. Of what's unread, I need to know what's received and what's not received. I use this information to build a dynamic where clause which filters a local datasource and displays the appropriate information.
Here's how the enum is put together:
public enum MemoView :int
{
InboundMemos = 1, // 0000 0001
InboundMemosForMyOrders = 3, // 0000 0011
SentMemosAll = 16, // 0001 0000
SentMemosNotReceived = 48, // 0011
SentMemosReceivedNotRead = 80, // 0101
SentMemosRead = 144, // 1001
Outbox = 272, //0001 0001 0000
OutBoxErrors = 784 //0011 0001 0000
}
Do you see what this does? By anding (&) with the "Inbox" enum value, InboundMemos, I know that InboundMemosForMyOrders is in the inbox.
Here's a boiled down version of the method that builds and returns the filter that defines a view for the currently selected folder:
private string GetFilterForView(MemoView view, DefaultableBoolean readOnly)
{
string filter = string.Empty;
if((view & MemoView.InboundMemos) == MemoView.InboundMemos)
{
filter = "<inbox filter conditions>";
if((view & MemoView.InboundMemosForMyOrders) == MemoView.InboundMemosForMyOrders)
{
filter += "<my memo filter conditions>";
}
}
else if((view & MemoView.SentMemosAll) == MemoView.SentMemosAll)
{
//all sent items have originating system = to local
filter = "<memos leaving current system>";
if((view & MemoView.Outbox) == MemoView.Outbox)
{
...
}
else
{
//sent sub folders
filter += "<all sent items>";
if((view & MemoView.SentMemosNotReceived) == MemoView.SentMemosNotReceived)
{
if((view & MemoView.SentMemosReceivedNotRead) == MemoView.SentMemosReceivedNotRead)
{
filter += "<not received and not read conditions>";
}
else
filter += "<received and not read conditions>";
}
}
}
return filter;
}
Extremely simple, but a neat implementation at a level of abstraction that doesn't typically require bitwise operations.
Usually bitwise operations are faster than doing multiply/divide. So if you need to multiply a variable x by say 9, you will do x<<3 + x which would be a few cycles faster than x*9. If this code is inside an ISR, you will save on response time.
Similarly if you want to use an array as a circular queue, it'd be faster (and more elegant) to handle wrap around checks with bit wise operations. (your array size should be a power of 2). Eg: , you can use tail = ((tail & MASK) + 1) instead of tail = ((tail +1) < size) ? tail+1 : 0, if you want to insert/delete.
Also if you want a error flag to hold multiple error codes together, each bit can hold a separate value. You can AND it with each individual error code as a check. This is used in Unix error codes.
Also a n-bit bitmap can be a really cool and compact data structure. If you want to allocate a resource pool of size n, we can use a n-bits to represent the current status.
Bitwise & is used to mask/extract a certain part of a byte.
1 Byte variable
01110010
&00001111 Bitmask of 0x0F to find out the lower nibble
--------
00000010
Specially the shift operator (<< >>) are often used for calculations.
Bitwise operators are useful for looping arrays which length is power of 2. As many people mentioned, bitwise operators are extremely useful and are used in Flags, Graphics, Networking, Encryption. Not only that, but they are extremely fast. My personal favorite use is to loop an array without conditionals. Suppose you have a zero-index based array(e.g. first element's index is 0) and you need to loop it indefinitely. By indefinitely I mean going from first element to last and returning to first. One way to implement this is:
int[] arr = new int[8];
int i = 0;
while (true) {
print(arr[i]);
i = i + 1;
if (i >= arr.length)
i = 0;
}
This is the simplest approach, if you'd like to avoid if statement, you can use modulus approach like so:
int[] arr = new int[8];
int i = 0;
while (true) {
print(arr[i]);
i = i + 1;
i = i % arr.length;
}
The down side of these two methods is that modulus operator is expensive, since it looks for a remainder after integer division. And the first method runs an if statement on each iteration. With bitwise operator however if length of your array is a power of 2, you can easily generate a sequence like 0 .. length - 1 by using & (bitwise and) operator like so i & length. So knowing this, the code from above becomes
int[] arr = new int[8];
int i = 0;
while (true){
print(arr[i]);
i = i + 1;
i = i & (arr.length - 1);
}
Here is how it works. In binary format every number that is power of 2 subtracted by 1 is expressed only with ones. For example 3 in binary is 11, 7 is 111, 15 is 1111 and so on, you get the idea. Now, what happens if you & any number against a number consisting only of ones in binary? Let's say we do this:
num & 7;
If num is smaller or equal to 7 then the result will be num because each bit &-ed with 1 is itself. If num is bigger than 7, during the & operation computer will consider 7's leading zeros which of course will stay as zeros after & operation only the trailing part will remain. Like in case of 9 & 7 in binary it will look like
1001 & 0111
the result will be 0001 which is 1 in decimal and addresses second element in array.
Base64 encoding is an example. Base64 encoding is used to represent binary data as a printable characters for sending over email systems (and other purposes). Base64 encoding converts a series of 8 bit bytes into 6 bit character lookup indexes. Bit operations, shifting, and'ing, or'ing, not'ing are very useful for implementing the bit operations necessary for Base64 encoding and decoding.
This of course is only 1 of countless examples.
I'm suprised no one picked the obvious answer for the Internet age. Calculating valid network addresses for a subnet.
http://www.topwebhosts.org/tools/netmask.php
Nobody seems to have mentioned fixed point maths.
(Yeah, I'm old, ok?)
Is a number x a power of 2? (Useful for example in algorithms where a counter is incremented, and an action is to be taken only logarithmic number of times)
(x & (x - 1)) == 0
Which is the highest bit of an integer x? (This for example can be used to find the minimum power of 2 that is larger than x)
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return x - (x >>> 1); // ">>>" is unsigned right shift
Which is the lowest 1 bit of an integer x? (Helps find number of times divisible by 2.)
x & -x
If you ever want to calculate your number mod(%) a certain power of 2, you can use yourNumber & 2^N-1, which in this case is the same as yourNumber % 2^N.
number % 16 = number & 15;
number % 128 = number & 127;
This is probably only useful being an alternative to modulus operation with a very big dividend that is 2^N... But even then its speed boost over the modulus operation is negligible in my test on .NET 2.0. I suspect modern compilers already perform optimizations like this. Anyone know more about this?
I use them for multi select options, this way I only store one value instead of 10 or more
it can also be handy in a sql relational model, let's say you have the following tables: BlogEntry, BlogCategory
traditonally you could create a n-n relationship between them using a BlogEntryCategory table
or when there are not that much BlogCategory records you could use one value in BlogEntry to link to multiple BlogCategory records just like you would do with flagged enums,
in most RDBMS there are also a very fast operators to select on that 'flagged' column...
When you only want to change some bits of a microcontroller's Outputs, but the register to write to is a byte, you do something like this (pseudocode):
char newOut = OutRegister & 0b00011111 //clear 3 msb's
newOut = newOut | 0b10100000 //write '101' to the 3 msb's
OutRegister = newOut //Update Outputs
Of course, many microcontrollers allow you to change each bit individually...
I've seen them used in role based access control systems.
There is a real world use in my question here -
Respond to only the first WM_KEYDOWN notification?
When consuming a WM_KEYDOWN message in the windows C api bit 30 specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is zero if the key is up
They are mostly used for bitwise operations (surprise). Here are a few real-world examples found in PHP codebase.
Character encoding:
if (s <= 0 && (c & ~MBFL_WCSPLANE_MASK) == MBFL_WCSPLANE_KOI8R) {
Data structures:
ar_flags = other->ar_flags & ~SPL_ARRAY_INT_MASK;
Database drivers:
dbh->transaction_flags &= ~(PDO_TRANS_ACCESS_MODE^PDO_TRANS_READONLY);
Compiler implementation:
opline->extended_value = (opline->extended_value & ~ZEND_FETCH_CLASS_MASK) | ZEND_FETCH_CLASS_INTERFACE;
I've seen it in a few game development books as a more efficient way to multiply and divide.
2 << 3 == 2 * 8
32 >> 4 == 32 / 16
Whenever I first started C programming, I understood truth tables and all that, but it didn't all click with how to actually use it until I read this article http://www.gamedev.net/reference/articles/article1563.asp (which gives real life examples)
I don't think this counts as bitwise, but ruby's Array defines set operations through the normal integer bitwise operators. So [1,2,4] & [1,2,3] # => [1,2]. Similarly for a ^ b #=> set difference and a | b #=> union.