I have a 2 bit number x stored in a single byte, and I would like to invert it, so that 0 is transformed to 3, 1 to 2, 2 to 1 and 3 to 0.
Isx^3be the correct way of doing this?
Also, for arbitrary N bit number x, will x^((1<<N)-1) be correct ?
x^3 is good for two bit numbers. If you have 4 bit numbers, use x ^ 15, or write it in hex, x ^ 0x0f if you want.
No, x^(N-1) will not work. What will work is x^(pow(2,N)-1)
Code :
((~x)&(0x3))
Test Code (Same piece of code should work in C++ too):
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Hello");
for(int i=0; i<=3; i++) {
System.out.println("Complement of " + i + " is " + (~i & 0x3));
}
}
Result:
Complement of 0 is 3
Complement of 1 is 2
Complement of 2 is 1
Complement of 3 is 0
Related
I'm writing a program that exchanges the values of the bits on positions 3, 4 and 5 with bits on positions 24, 25 and 26 of a given 32-bit unsigned integer.
So lets say I use the number 15 and I want to turn the 4th bit into a 0, I'd use...
int number = 15
int newnumber = number & (~(1 << 3));
// output is 7
This makes sense because I'm exchanging the 4th bit from 1 to 0 so 15(1111) becomes 7(0111).
However this wont work the other way round (change a 0 to a 1), Now I know how to achieve exchanging a 0 to a 1 via a different method, but I really want to understand the code in this method.
So why wont it work?
The truth table for x AND y is:
x y Output
-----------
0 0 0
0 1 0
1 0 0
1 1 1
In other words, the output/result will only be 1 if both inputs are 1, which means that you cannot change a bit from 0 to 1 through a bitwise AND. Use a bitwise OR for that (e.g. int newnumber = number | (1 << 3);)
To summarize:
Use & ~(1 << n) to clear bit n.
Use | (1 << n) to set bit n.
To set the fourth bit to 0, you AND it with ~(1 << 3) which is the negation of 1000, or 0111.
By the same reasoning, you can set it to 1 by ORing with 1000.
To toggle it, XOR with 1000.
I want to use parity check function in a loop to make an event that happens every second times. But all the functions I found to watch parity don't work.
Even the most simple ones, like this:
unsigned int v;
bool parity = false;
while (v)
{
parity = !parity;
v = v & (v - 1);
}
Can give me the same value for an even number and for an odd number.
How to do it well? Or maybe, are there any other ways to to make an event that happens in every second round through the loop?
It seems like you're misunderstanding the meaning of "parity" as it's normally used in the world of computers. The code you've shown sets parity to false if the binary representation of v has an even number of set bits, and to true if it has an odd number of set bits. The concept of parity has nothing to do with v being even or odd itself. Some examples:
Number (base 10) Number (base 2) Parity
0 0 0
1 1 1
2 10 1
3 11 0
4 100 1
5 101 0
6 110 0
7 111 1
. . .
. . .
. . .
12498741 1101 1110 1101 0111 0011 0101 0
. . .
. . .
. . .
If you really do want to check if a number is even or odd, you can use:
bool odd = v & 1;
bool even = !(v & 1);
Which are equivalent to the % expression used in #user1118321's answer.
Try this:
bool isEven = ((v % 2) == 0);
This assumes v is the variable you wish to test for evenness. This is modulo arithmetic.
Here is the problem:
There are 2*N+1 integers in one array, and there are N pair int numbers, i,e, two 1, or two 3 etc,so there is only one int number , which has no pair.
The question is how to find this number with high efficient algorithm.
Thanks for any clues or comments.
Ok, Ok, here's an explanation of my comment. :-/
missingNum = 0
for each value in list
missingNum = missingNum ^ value //^ = xor
next
print(missingNum)
That's a linear algorithm, O(n).
So what's happening here? Say, we have [2,1,3,1,2], for those familiar with XOR operator, know that 1 ^ 1 = 0, 0 ^ 0 = 0, and 1 ^ 0 = 1, 0 ^ 1 = 1 (remember there's no carry)
So essentially, when we XOR a sequence of bits (100110111), and it has even numbers of 1, each will XOR themselves to zero...if the number of 1's are odd, the XOR yields a 1
So in our example, starting from lsb
2 : 0010
1 : 0001
3 : 0011
1 : 0001
2 : 0010
lsb bit: 0 ^ 1 ^ 1 ^ 1 ^ 0 : 1
2nd bit: 1 ^ 0 ^ 1 ^ 0 ^ 1 : 1
3rd bit: 0 ^ 0 ^ 0 ^ 0 ^ 0 : 0
4th bit: 0 ^ 0 ^ 0 ^ 0 ^ 0 : 0
So our missing number is
0011 = 3
You can find more universal answer in this question. If you assume n=2, m=1 you'll get what you want.
But, as st0le said, in your case XOR should be enough.
If I understand the question correctly, you've got an array containing an odd number of integer values, consisting of a number of integers that appear twice plus one integer that appears only once. For example, the array might look like this:
[3, 41, 6, 6, 41]
where 6 and 41 are both repeated and 3 is unique.
It would be good to know if there are any other constraints. For example:
Is the array sorted? (If so, this is a simple problem to solve in O(N) time with no requirement for temporary storage.)
Can the unpaired integer be the same as an integer in a pair? e.g. is [1, 2, 2, 2, 1] a valid input, being a pair of 1s, a pair of 2s and an unpaired 2?
Assuming the array isn't sorted, here's one solution, expressed in pseudocode, which runs in O(N) time and requires at most around half the storage space again of the original array.
SEEN = []
for N in ARRAY:
if N in SEEN:
remove N from SEEN
else:
add N to SEEN
if size of SEEN != 1:
error - ARRAY doesn't contain exactly 1 un-paired value
else:
answer = SEEN[0]
Here's a sample implementation using an NSMutableDictionary to store seen values, assuming that the source array is a plain C array.
#import <Foundation/Foundation.h>
int main(int argc, char argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int array[9] = {3, 4, 5, 6, 7, 6, 5, 4, 3};
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:16];
for (int i = 0; i < sizeof(array)/sizeof(int); i++) {
NSNumber *num = [NSNumber numberWithInt:array[i]];
if ([d objectForKey:num]) {
[d removeObjectForKey:num];
} else {
[d setObject:[NSNull null] forKey:num];
}
}
if ([d count] == 1) {
NSLog(#"Unpaired number: %i", [[[d keyEnumerator] nextObject] intValue]);
} else {
NSLog(#"Error: Expected 1 unpaired number, found %u", [d count]);
}
[pool release];
return 1;
}
And here it is running:
$ gcc -lobjc -framework Foundation -std=c99 demo.m ; ./a.out
2010-12-25 11:23:21.426 a.out[17544:903] Unpaired number: 7
I have the following bottleneck function.
typedef unsigned char byte;
void CompareArrays(const byte * p1Start, const byte * p1End, const byte * p2, byte * p3)
{
const byte b1 = 128-30;
const byte b2 = 128+30;
for (const byte * p1 = p1Start; p1 != p1End; ++p1, ++p2, ++p3) {
*p3 = (*p1 < *p2 ) ? b1 : b2;
}
}
I want to replace C++ code with SSE2 intinsic functions. I have tried _mm_cmpgt_epi8 but it used signed compare. I need unsigned compare.
Is there any trick (SSE, SSE2, SSSE3) to solve my problem?
Note:
I do not want to use multi-threading in this case.
Instead of offsetting your signed values to make them unsigned, a slightly more efficient way would be to do the following:
use _mm_min_epu8 to get the unsigned min of p1, p2
compare this min for equality with p2 using _mm_cmpeq_epi8
the resulting mask will now be 0x00 for elements where p1 < p2 and 0xff for elements where p1 >= p2
you can now use this mask with _mm_or_si128 and _mm_andc_si128 to select the appropriate b1/b2 values
Note that this is 4 instructions in total, compared with 5 using the offset + signed comparison approach.
You can subtract 127 from your numbers, and then use _mm_cmpgt_epi8
Yes, this can be done in SIMD, but it will take a few steps to make the mask.
Ruslik got it right, I think. You want to xor each component with 0x80 to flip the sense of the signed and unsigned comparison. _mm_xor_si128 (PXOR) gets you that -- you'll need to create the mask as a static char array somewhere before loading it into a SIMD register. Then _mm_cmpgt_epi8 gets you a mask and you can use a bitwise AND (eg _mm_and_si128) to perform a masked-move.
Yes, SSE will not work here.
You can improve this code performance on multi-core computer by using OpenMP:
void CompareArrays(const byte * p1Start, const byte * p1End, const byte * p2, byte * p3)
{
const byte b1 = 128-30;
const byte b2 = 128+30;
int n = p1End - p1Start;
#pragma omp parallel for
for (int i = 0; i < n; ++p1, ++i)
{
p3[i] = (p1[i] < p2[i]) ? b1 : b2;
}
}
Unfortunately, many of the answers above are incorrect. Let's assume a 3-bit word:
unsigned: 4 5 6 7 0 1 2 3 == signed: -4 -3 -2 -1 0 1 2 3 (bits: 100 101 110 111 000 001 010 011)
The method by Paul R is incorrect. Suppose we want to know if 3 > 2. min(3,2) == 2, which suggests yes, so the method works here. Now suppose we want to know if if 7 > 2. The value 7 is -1 in signed representation, so min(-1,2) == -1, which suggests wrongly that 7 is not greater than 2 unsigned.
The method by Andrey is also incorrect. Suppose we want to know if 7 > 2, or a = 7, and b = 2. The value 7 is -1 in signed representation, so the first term (a > b) fails, and the method suggests that 7 is not greater than 2.
However, the method by BJobnh, as corrected by Alexey, is correct. Just subtract 2^(n-1) from the values, where n is the number of bits. In this case, we would subtract 4 to obtain new corresponding values:
old signed: -4 -3 -2 -1 0 1 2 3 => new signed: 0 1 2 3 -4 -3 -2 -1 == new unsigned 0 1 2 3 4 5 6 7.
In other words, unsigned_greater_than(a,b) is equivalent to signed_greater_than(a - 2^(n-1), b - 2^(n-1)).
use pcmpeqb and be the Power with you.
Is there any clever way to mix two bit sequences in such way that bits from first sequence will be on odd places, and bits from second sequence will be on even places.
Both sequences are no longer than 16b so output will fit into 32bit integer.
Example:
First sequence : 1 0 0 1 0 0
Second sequence : 1 1 1 0 1 1
Output : 1 1 0 1 0 1 1 0 0 1 0 1
I thought about making integer array of size 2^16 and then the output would be:
arr[first] << 1 | arr[second]
Have a look at http://graphics.stanford.edu/~seander/bithacks.html#InterleaveTableLookup This page lists the obvious (for loop) and 3 optimized algorithms. Neither one is particularly simple but without testing I'd guess they are considerably faster than a loop.
in C#:
public Int32 Mix(Int16 b1, Int16 b2)
{
Int32 res = 0;
for (int i=0; i<16; i++)
{
res |= ((b2 >> i) & 1) << 2*i;
res |= ((b1 >> i) & 1) << 2*i + 1;
}
return res;
}