Do you know your bitwise operators?
quaxio.com
quaxio.com
Expected assignment, comment or return statement but " " found.
When trying to get rid of parse errors, I did something like "return x" and it says Solution did not return correct output for x=1. Expected output: 1, got: 0
Which is clearly not right.Just tried doing "return 1" and still got
Solution did not return correct output for x=1. Expected output: 1, got: 0For what it's worth, here's my answer: 1>>(x&~(~x+1))&~(1>>x) . (I didn't figure out that the tester was broken before I developed my answer.)
I tested it with positive integers on Python. I haven't tried it with negatives in Javascript.
The '(x&~(~x+1))' is a work-around to get 'x&(x-1)', which is 0 if x is a power of two. The (1>> value) is a workaround to get "value == 0". Thus, '1>>(x&~(~x+1))' means 'is x a power of two?'
The ~(1>>x) means 'is x == 0'. Combine the two together gives 1 if a single bit is set, else 0.
function one_bit(x) {
return x & (x-1) == 0
}
Only to see this error: Expected "}" or comment but "&" found.
WATfunction one_bit(x) { return x & (x-1) == 0 ? 1 : 0; }
function one_bit(x) {
return 1
}
Solution did not return correct output for x=1. Expected output: 1, got: 0
umm... okOops, i'll fix it.
int FLAG_1 = 1;
int FLAG_2 = 2;
int FLAG_3 = 4; //These would actually probably be formatted like (1 << N)
...
And then pass in your options to a function like f(... FLAG_1+FLAG_2) so you can have an optional number of flags in a single argument.- Interacting with hardware that uses certain bits in a register to control behavior - for example, Arduino digital ports [2]
- Doing arithmetic extra-fast with numbers that are powers of two - modulo becomes bitwise-and, division and multiplication become shifts
[1] http://en.wikipedia.org/wiki/List_of_monochrome_and_RGB_pale...
Example, a microcontroller has an 8 bit status register. Each bit controls some hardware function. You wish to change bit 5, but you can't change anything else because it would cause unwanted side effects. So this rules out simply saying myregister = 0b00001000.
Common solution is to make a macro like:
#define setbit(BYTE,BIT) BYTE |= (1 << BIT)
Thus you can say I want to set bit 5 in my register by calling setbit(foo, 5) while keeping the rest of the byte intact. There are analogous macros for clearing and toggling bits.
Or you might want to perform an operation based on a particular bit in a byte, e.g. byte 5 is a status flag that tells you when a timer has overflowed.
#define getbit(BYTE, BIT) !!(BYTE & ~(1 << BIT))
Then you can say:
if( getbit(myregister, 5)){ // do something }
Fun fun :)
The best I could come up with is:
function one_bit(x) { return 1 >>> (x & (x + ~0)) }
("x + ~0" is equivalent to "x - 1")
But this doesn't work when x is 0 All other case should be fine, afaik.