C Swapping with shifting bits - c

Here is a program to swap two numbers with out using temporary variable and using shifting operations:
#include <stdio.h>
#include <conio.h>
int main(void)
{
int a,b,i,j;
clrscr();
printf(“Enter two integers: “);
scanf(“%d%d”,&a,&b);
printf(“a=%d,b=%d\n”,a,b);
for(i = 0; i < 16; i++)
{
if((a & (1 << i)) ^ (b & (1 << i)))
{
a = a ^ (1 << i);
b = b ^ (1 << i);
}
}
printf(“a=%d,b=%d”,a,b);
getch();
return 0;
}
My question is what is significance of 1 in this program?
I know the method of xoring that works as follows
a = a^b;
b = a^b;
a = a^b;
but I don't know how above program works?

It toggles each bit if only one is set.
c = a & (1 << i) = true if the ith bit of a is set
d = b & (1 << i) = true if the ith bit of b is set
| c | d | Action | c' | d' |
-------------------------------------
| 0 | 0 | Do nothing | 0 | 0 |
| 0 | 1 | Toggle the bits | 1 | 0 |
| 1 | 0 | Toggle the bits | 0 | 1 |
| 1 | 1 | Do nothing | 1 | 1 |

1 has one bit on the rightmost position set. 1<<i has one bit on place i set. This program loops through each bit, and swaps them if they are different.
a&(1<<i) tests if a has bit i set.
((a&(1<<i))^(b&(1<<i))) tests if bit i in a and b are different.
a=a^(1<<i) toggles bit i.

It's similar to the XOR trick, but swaps only a single bit at a time and only if this bit actually differs in a and b.
1<<i has bit i set to 1 and all other bits 0.
Also, this does not swap two numbers without using a temporary variable. It uses the temporary i.

Related

Binary addition

I am trying to understand how Bitwise operators work in C, but I have an misunderstanding about the << operator.
I have the following code:
#include <stdio.h>
int Add(int x, int y);
int Add(int x, int y)
{
while ( y != 0 ) /// Iterate till there is no carry
{
int carry = x & y; /// carry now contains common set bits of x and y
x = x ^ y; /// Sum of bits of x and y where at least one of the bits is not set
y = carry << 1; /// Carry is shifted by one so that adding it to x gives the required sum
}
return x;
}
int main( void )
{
printf( "%d", Add( 13, 17 ) );
return 0;
}
If I understand correctly works like this:
First Iteration:
|=======================================|
| |
| while ( y != 0 ) |
| while ( 17 != 0 ) |
| while ( 10001 != 00000 ) |
| |
| c = x & y; |
| 1 = 13 & 17 |
| 00001 = 01101 & 10001 |
| |
| x = x ^ y |
| 28 = 13 ^ 17 |
| 11100 = 01101 ^ 10001 |
| |
| y = c << 1 |
| 17 = 1 << 1 |
| 10001 = 00001 << 00001 |
| 00010 = 00001 << 00001 |
| |
|=======================================|
Second Iteration:
|=======================================|
| |
| while ( y != 0 ) |
| while ( 2 != 0 ) |
| while ( 00010 != 00000 ) |
| |
| c = x & y; |
| 0 = 28 & 2 |
| 00000 = 11100 & 00010 |
| |
| x = x ^ y |
| 30 = 28 ^ 2 |
| 11110 = 11100 ^ 00010 |
| |
| y = c << 1 |
| 2 = 0 << 1 |
| 00010 = 00000 << 00001 |
| 00000 = 00000 << 00001 |
| |
|=======================================|
Then Y becomes 0 and X returns 30.
Now in the following code I have an issue:
#include <stdio.h>
int main( void )
{
int x = 13;
int y = x << 1; /// 11010 = 01101 << 00001
x = 0 << 1; /// 00000 = 00000 << 00001
printf("y = %d\n", y ); /// 26 | 11010
printf("x = %d\n", x ); /// 26 | 11010
return 0;
}
Here if I understand right we shift all bits one to the left:
int y = x << 1; /// 11010 = 01101 << 00001
But what exactly happens here:
x = 0 << 1; /// 00000 = 00000 << 00001
Does x get cleared and filled with the rezult of 0 << 1 ?
Does x get cleared and filled with the rezult of 0 << 1 ?
x is just assigned the value of the expression 0 << 1. Zero left or right shifted by any amount remains 0.
So this means that the representation of the First and Second Iteration is correct?
It is correct, except that substitution of the old values of variables (on the lhs) is a bit confusing as in the following cases.
17 = 1 << 1
10001 = 00001 << 00001
and
2 = 0 << 1
00010 = 00000 << 00001
Instead depict it as:
y = 1 << 1
y = 00001 << 00001
and
y = 0 << 1
y = 00000 << 00001
n << k is actually n * (2^k) as long as you have enough bits available to keep all of the resulting bits. So 0 << k is 0 * (2^k) = 0 whatever the (positive integer) value of k is.
Note that for usual 32 bit integers, a number on p = 17 bits or more, like 65537 (0x0001_0001), will stop behaving like the multiplication once k is greater or equal to (32+1)-p = (32+1)-17 = 16, as for example 65537 << 16 is 0x1_0001_0000 which is using 33 bits and is truncated to 0x0001_0000 = 65536.
With 65536 << 15 you may also start having strange results as the result, 0x1000_0000, is changing the left most bit, which is the sign bit if you're not using unsigned values...

Why this type of power function work?

res = 1;
for ( i = 1; i <= n; i <<= 1 ) // n = exponent
{
if ( n & i )
res *= a; // a = base
a *= a;
}
This should be more effective code for power and I don't know why this works.
First line of for() is fine I know why is there i <<= i. But I don't understand the line where is: if ( n & i ). I know how that works but I don't know why...
Let us say you have a binary representation of an unsigned number. How do you find the decimal representation?
Let us take a simple four bit example:
N = | 0 | 1 | 0 | 1 |
-----------------------------------------
| 2^3 = 8 | 2^2 = 4 | 2^1 = 2 | 2^0 = 1 |
-----------------------------------------
| 0 | 4 | 0 | 1 | N = 4 + 1 = 5
Now what would happen if the base wasn't fixed at 2 for each bit but instead was the square of the previous bit and you multiply the contribution from each bit instead of adding:
N = | 0 | 1 | 0 | 1 |
----------------------------
| a^8 | a^4 | a^2 | a^1 |
----------------------------
| 0 | a^4 | 0 | a^1 | N = a^4 * a^1 = a^(4+1) = a^5
As you can see, the code calculate a^N

In C: what does var = x | y | z; mean?

So I've recently started working with TI's CC2650 device and am trying to learn how to program it by studying some of their sample applications. I see a lot of variables declared in this format and I have no clue what it means:
var1 = x | y | z;
In the example above, var1 is of type uint8_t.
| is the binary bitwise or operator. For example: 0x00ff | 0xff00 is 0xffff.
bitwise OR operator, so if you have x = 5 (101) y = 8 (1000) and z = 20 (10100), values in parenthesis are binary values so
x | y | z = 101 | 1000 | 10100 = 11101
The operator | in C is known a s bitwise OR operator. Similar to other bitwise operators (say AND &), bitwise OR only operates at the bit level. Its result is a 1 if one of the either bits is 1 and zero only when both bits are 0. The | which can be called a pipe! Look at the following:
bit a bit b a | b (a OR b)
0 0 0
0 1 1
1 0 1
1 1 1
In the expression, you mentioned:
var1 = x | y | z | ...;
as there are many | in a single statement, you have to know that, bitwise OR operator has Left-to-right Associativity means the operations are grouped from the left. Hence the above expression would be interpreted as:
var1 = (x | y) | z | ...
=> var1 = ((x | y) | z) | ...
....
Read more about Associativity here.

homework: Trying to sort out what operation I am attempting to compute C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Sorry for asking you guys and not my professor. (its due in a couple of hours and she is not available)
but I am just looking for a point in the right directions.
one piece of what I am writing tonight states two things...
Single-character versions of the C logical operators:
& for && (logical AND)
| for || (logical OR)
! for logical NOT
and this... as example output.
Enter an expression: (0 & 1) | (1 & 1)
Result: (0 & 1) | (1 & 1) = true
My pseudo logic is to take the input of '&' or '|' and have it return as '&&' or '||' and throw it all back together based on the entered expression and let the program do the math.
But what I don't understand is what would make the above expression evaulwate to true? and or false? What should I research to lean more about the above expression? and what makes it true or false?
The concept of true and false in C is of integers 0 for false and a non-zero number for true.
"single" boolean operators like &, |, ~ and ^ are called bitwise operators.
They work on two numbers, bit by bit - following the logic tables respectively - AND, OR, ONE-COMPLEMENT(not) and XOR.
So, your expression:
(0 & 1) | (1 & 1) is true because 0 & 1 = 0, 1 & 1 = 1 and 0 | 1 is 1. which is true.
What could turn this into false is if the expression was combined with an & instead of | like so:
(0 & 1) & (1 & 1) = false.
Truth table of AND:
+---------------+---------+
| A + B | A & B |
+---------------+---------+
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
+---------------+---------+
Truth table of OR:
+---------------+---------+
| A + B | A | B |
+---------------+---------+
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
+---------------+---------+
However, since C99, true and false are reserved words, and will evaluate to 0 and 1 internally - The answer posted above applies for C99 as well as C89
Look at it this way:
(0 & 1) | (1 & 1)
= (0 and 1) or (1 and 1)
= (false and true) or (true and true)
= (false) or (true)
= true
Further reading at wikipedia
Thanks for everyone's input. Really helped.
int logicalCheck (int a, int x, int b) {
// let 88 = true
// let 89 = false
if (x == '&') {
if (a == b) {
return 88;
}
if (a != b) {
return 89;
}
}
if (x == '|') {
if ((a == b && a) || b != 0) {
return 88;
}
if (a || b == 0) {
return 89;
}
}
return 0;

If I have a truth table, is there a way of determining the bitwise expression I need for that truth table?

I am attempting to do the following in c:
unsigned int mask;
unsigned int previous;
unsigned int new;
unsigned int out;
for( int i = 0; i < 8; ++i )
{
bool bit_set = GET_BIT( mask, i );
// If the mask bit is true, use the new bit, otherwise use the previous bit
SET_BIT( out, i, GET_BIT( bit_set ? new : previous, i ) );
}
However I think there may be an easier and quicker way using bitwise operations. I have the truth table but I don't know how to get the expression I need.
Truth table is:
m | p | n | o
0 | 0 | 0 | 0
1 | 0 | 0 | 0
0 | 1 | 0 | 1
1 | 1 | 0 | 0
0 | 0 | 1 | 0
1 | 0 | 1 | 1
0 | 1 | 1 | 1
1 | 1 | 1 | 1
How would I go about working this out?
Use Karnaugh Map - there is a solver available online. Pick "three values", enter the expected results for all eight combinations, and use the expression the solver produces:
F(m, p, n) = (p & !n) | (m & n)
EDIT : You can expand this solution to do the whole byte at once, rather than doing it one bit at a time, by using the ~ bitwise NOT operator:
result = (mask & new) | (~mask & previous);
If the mask bit is true, use the new bit, otherwise use the previous
bit
The natural way to express this (to me) is (mask & new) | (~mask & previous). That is to say, mask corresponding bits from new and previous, and add them together using OR.

Resources