R
Ricky
how to implement logical equivalence (==) or negation (!) for binary
numbers using only binary operators such as ~ & ^ | + << >>?
numbers using only binary operators such as ~ & ^ | + << >>?
how to implement logical equivalence (==) or negation (!) for binary
numbers using only binary operators such as ~ & ^ | + << >>?
how to implement logical equivalence (==) or negation (!) for binary
numbers using only binary operators such as ~ & ^ | + << >>?
I would just use "==" and "!".
However, consider:
0 xor 0 == 0
0 xor 1 == 1
1 xor 0 == 1
1 xor 1 == 0
Note the properties:
Xor returns 0 iff the bits are the same.
If you xor with 1, you "toggle" the bit.
How could you use these properties to emulate "==" and "!"?
/* Return 1u if any bit is set in "x", return 0u otherwise. */
unsigned
mig32(uint32_t x)
{
x |= x >> 16; /* "condensed" to bits 15 .. 0 */
x |= x >> 8; /* "condensed" to bits 7 .. 0 */
x |= x >> 4; /* "condensed" to bits 3 .. 0 */
x |= x >> 2; /* "condensed" to bits 1 .. 0 */
x |= x >> 1; /* "condensed" to bit 0 */
return x & 1u;
}
{
uint32_t a, b;
/* ... */
mig32(a) ^ 1u; /* boolean-neg */
mig32(a) ^ mig32(b) ^ 1u; /* boolean-eq; IOW, negated boolean-neq */
I'm sure you meant mig32(a^b)^1;
/*
* int compare(int, int):
* compares two numbers and returns 1 if they are equal
*/
#include <limits.h>
int compare(int a, int b) {
unsigned int values[UINT_MAX];
unsigned int idx;
unsigned int ua = a,
ub = b;
int zcount = 0;
if(ua < 1 || ub < 1)
ua += 73, ub += 73;
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.