Trailing Zeros - C - c

I need a program that returns the number of trailing zeros in the binary rapresentation of a number. I found online a function written in C but I don't understand how it works
This is the function:
unsigned tzr(unsigned x)
{
unsigned n; /* number of bits */
n = 0;
if (!(x & 0x0000FFFF)) { n += 16; x >>= 16; }
if (!(x & 0x000000FF)) { n += 8; x >>= 8; }
if (!(x & 0x0000000F)) { n += 4; x >>= 4; }
if (!(x & 0x00000003)) { n += 2; x >>= 2; }
n += (x & 1) ^ 1; // anyway what does this do ?
return n;
}
Now I've really tried to understand how this works but I don't get it.
I really need someone who could explain it to me, I find this code very complicated.
And about those hexadecimal constants, these are their values:
0x0000FFFF = 65535
0x000000FF = 255
0x0000000F = 15
0x00000003 = 3
Now, why the program uses those values and makes a bitwise AND with the number?
Then I know that if you want to handle big numbers you must
use a while instead of the first if statement, like this:
while (!(x & 0x0000FFFF)) { bits += 16; x >>= 16; } // why should I need this ?
But I don't know why ! What's the difference about using a while instead of an if in this case?

The hexadecimal constants are AND'ed with the value to check whether the last [number] of digits is zero.0x0000FFFF is a number with 16 ones in binary. If the value AND'ed with 0x0000FFFF is equal to 0, you know that the last 16 digits are zeroes (the ifs check for the reverse of that statement). Going further 0x000000FF is a number with 8 ones in binary. The next check is for the last 8 digits, next for 4 digits and the last one for 2 digits as 0x00000003 is 11 in binary. After the checks the numbers are shifted to check whether further digits are also zero. This way we can check for any number of trailing zeroes as the values are powers of 2 and adding them works exactly like working with binary.
Last statement checks for the last digit after all the previous shifting is done - AND with 1 and checking if it's 0 or 1 with a XOR(^).
This program checks numbers with 32 bits. You can change the first if to a while to check larger, e.g. 64-bit, numbers. Another way is to check with 0xFFFFFFFF and then shift 32 bits at once.

The line n += (x & 1) ^ 1 checks the least significant bit (LSB) of the current state of x. If the LSB is a 1 then (x & 1) yeilds 1 which is then XORed (the caret symbol '^' means to XOR two values) with 1 to give 0 (1 ^ 1 == 0). When x has a 0 in the LSB and is XORed with 1 it yeilds 1 (0 ^ 1 == 1).

!(x&0x0000FFFF) will be true only when the last 16 bits of x are all 0's.
The & is a bitwise and, and 0x0000FFFFF is the number ending in 16 1's.
So the result of the and is 0 iff all 16 trailing bits are 0 (and so FALSE and 1 reverses the truth value) because if there is at least one 1 among the last 16, the and with the corresponding 1 in the constant will be 1. So then the and is not 0 (so TRUE and ! reverses the truth value).
So the code says: if the last 16 bits are 1, add 16 to n and throw the last 16 bits away (that is what x >>= 16 does).
The next line says in a similar way:
if the last 8 bits of the (possibly shortened x) are 0 ,add 8 to n and throw the rightmost 8 bits away, and so on for 4 and 2 bits as well
The last line adds 1 if the rightmost bit (x&1) is 0, otherwise 0 (1^1 = 0).
So say if the righmost 15 bits are 0, the first if will be false , n remains 0.
The second will be true, as we have more than 8. Tne new x will have 7 0-bits,
and n=8.
The third will also be true (we have still 4 or more), so the new x has 3 0-bits after the shift and n=12.
The fourth will also be true (2 or more 0's) so the new x has 1 0-bit and n=14.
The final statement adds 1, so get n=15.
Because we use decreasing powers of 2 we don't need a loop. We get all possible n values this way (except 32, for input x=0, a fully correct function should maybe check for that and early abort.

n += (x & 1) ^ 1; // anyway what does this do ?
This checks the right-most bit. Either it is set or NOT set.
If it is set, then there is NOT another 0 to add onto the running total of trailing zeros, so n+=0.
If it is NOT set, then there is another 0 to add onto the running total of trailing zeros, so n+=1.
Also, your example does NOT compile, it is missing two ; as follows:
unsigned tzr(unsigned x)
{
unsigned n; /* number of bits */
n = 0;
if (!(x & 0x0000FFFF)) { n += 16; x >>= 16; }
if (!(x & 0x000000FF)) { n += 8; x >>= 8; }
if (!(x & 0x0000000F)) { n += 4; x >>= 4 } // won't compile due to missing ;
if (!(x & 0x00000003)) { n += 2; x >>= 2 } // won't compile due to missing ;
n += (x & 1) ^ 1; // anyway what does this do ?
return n;
}
Also, you can always try printing out data, for example, every power of 2 has multiple trailing zeros, but only odd amounts of trailing zeros are incremented by an additional 1 from n += (x & 1) ^ 1;...
cout << tzr(9) << endl << endl; // 1001 (not a power of two )
cout << tzr(8) << endl << endl; // 1000 (8>>2 & 1)^1==1
cout << tzr(4) << endl << endl; // 0100 (4>>2 & 1)^1==0
cout << tzr(2) << endl << endl; // 0010 ( 2 & 1)^1==1
cout << tzr(1) << endl << endl; // 0001 ( 1 & 1)^1==0
tzr(9) == 0 ==> 0 + (9 & 1) ^ 1 == 0 + 0
tzr(8) == 3 ==> 2 + (8>>2 & 1) ^ 1 == 2 + 1
tzr(4) == 2 ==> 2 + (4>>2 & 1) ^ 1 == 2 + 0
tzr(2) == 1 ==> 0 + (2 & 1) ^ 1 == 0 + 1
tzr(1) == 0 ==> 0 + (1 & 1) ^ 1 == 0 + 0
Program ended with exit code: 0

You say, "I need a program that returns the number of trailing zeros in the binary rapresentation of a number." But does it have to be the program you found? Here's an alternative solution that implements tzr() in exactly one line of code,
#include <stdio.h>
#include <stdlib.h>
int tzr(int n) { /* --- every time n is even, add 1 and check n/2 --- */
return ( (n/2)*2 == n? 1+tzr(n/2) : 0 ); }
int main ( int argc, char *argv[] ) { /* --- test driver --- */
int n = (argc>1? atoi(argv[1]) : 1000);
printf("tzr(%d) = %d\n", n,tzr(n)); }
Is that any easier to understand?
(P.S. You could use bit masks and shifts instead of my divides and multiplies. That might be a little more efficient, but I thought my way might be a little more straightforward to read.)

Related

How to extract bits from a number in C?

I need to extract specific part (no of bits) of a short data type in C.
Fox example, i have a binary of 45 as 101101 and i just want 2 bits in middle such as (10)
I started with C code 2 days ago so don't given a lot of functions.
How do i extract them ?
Please search for bit-wise operations for more general information, and bit masking for your specific question. I wouldn't recommend to jump to bits if you are new to programming though.
The solution will slightly change depending on whether your input will be fixed in length. If it won't be fixed, you need to arrange you mask accordingly. Or you can use a different method, this is probably simplest way.
In order to get specific bits that you want, you can use bitmasking.
E.g you have 101101 and you want those middle two bits, if you & this with 001100, only bits that are 1 on the mask will remain unchanged in the source, all the other bits will be set to 0. Effectively, you will have those bits that you are interested in.
If you don't know what & (bitwise and) is, it takes two operands, and returns 1 only if first AND second operands are 1, returns 0 otherwise.
input : 1 0 1 1 0 1
mask : 0 0 1 1 0 0
result : 0 0 1 1 0 0
As C syntax, we can do this like:
unsigned int input = 45;
unsigned int mask = 0b001100; // I don't know if this is standard notation. May not work with all compilers
// or
unsigned int mask = 12; // This is equivalent
unsigned int result = input & mask; // result contains ...001100
As yo can see, we filtered the bits we wanted. The next step depends on what you want to do with those bytes.
At this point, the result 001100 corresponds to 12. I assume this is not really useful. What you can do is, you can move those bits around. In order to get rid of 0s at the right, we can shit it 2 bits to the right. For this, we need to use >> operator.
0 0 1 1 0 0 >> 2 ≡ 0 0 0 0 1 1
result = result >> 2; // result contains ...011
From there, you can set a bool variable to store each of them being 1 or 0.
unsigned char flag1 = result & 0b01; // or just 1
unsigned char flag2 = result & 0b10; // or just 2
You could do this without shifting at all but this way it's more clear.
You need to mask the bits that you want to extract. If suppose you want to create mask having first 4 bits set. Then you can do that by using:
(1 << 4) - 1
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void print_bin(short n)
{
unsigned long i = CHAR_BIT * sizeof(n);
while(i--)
putchar('0' + ((n >> i) & 1));
printf("\n");
}
int main()
{
short num = 45; /* Binary 101101 */
short mask = 4; /* 4 bits */
short start = 0; /* Start from leftmost bit
position 0 */
print_bin((num >> start) & ((1 << mask) - 1)); /* Prints 1101 */
mask = 2; /* 2 bits */
start = 1; /* start from bit indexed at position 1 */
print_bin((num >> start) & ((1 << mask) - 1)); /* Prints 10 */
return 0;
}
Output:
0000000000001101
0000000000000010

bit manipulation: clearing range of bits

I'm preparing for an interview using the text, "Cracking the Coding Interview" by Gayle Laakman McDowell. On the section covering bit manipulation, there are two functions that are provided, but I don't quite understand how it works.
// To clear all bits from the most significant bit through i (inclusive), we do:
int clearMSBthroughI(int num, int i) {
int mask = (1 << i) - 1;
return num & mask;
}
// To clear all bits from i through 0 (inclusive), we do:
int clearBitsIthrough0(int num, int i) {
int mask = ~(((1 << (i+1)) - 1);
return num & mask;
}
In the first function, I understand what (1 << i) does of course, but what I'm not sure of is how subtracting 1 from this value affects the bits (i.e., (1 << i) - 1)).
I basically have the same confusion with the second function. To what effects, specifically on the bits, does subtracting 1 from ((1 << (i+1)) have? From my understanding, ((1 << (i+1)) results in a single "on" bit, shifted to the left i+1 times--what does subtracting this by 1 do?
Thanks and I hope this was clear! Please let me know if there are any other questions.
For those who by some chance have the text I'm referencing, it's on page 91 in the 5th Edition.
let's assume i= 5
(1 << i) give you 0100000 the 1 is placed in the 6th bit position
so now if we substract 1 from it, then we get 0011111 ==> only the 5 first bit are set to 1 and others are set to 0 and that's how we get our mask
Conclusion: for a giving i the (1 << i) -1 will give you a mask with the i first bits set to 1 and others set to 0
For the first question:
lets say i = 5
(1 << i ) = 0010 0000 = 32 in base 10
(1 << i ) -1 = 0001 1111 = 31
So a & with this mask clears the most significant bit down to i because all bit positions above and including index i will be 0 and any bellow will be 1.
For the second question:
Again lets say i = 5
(1 << (i + 1)) = 0100 0000 = 64 in base 10
(1 << (i + 1)) - 1 = 0011 1111 = 63
~((1 << (i + 1)) - 1) = 1100 0000 = 192
So a & with this masks clears bits up to index i
First Function:
Let's take i=3 for example. (1 << i) would yield 1000 in binary. Subtracting 1 from that gives you 0111 in binary (which is i number of 1's). ANDing that with the number will clear all but the last i bits, just like the function description says.
Second Function:
For the second function, the same applies. If i=3, then ((i << (i+1)) - 1) gives us 01111. The tilde inverts the bits, so we have 10000. It's important to do it this way instead of just shifting i bits left, because there could be any number of significant bits before our mask (so 10000 could be 8 bits long, and look like 11110000. That's what the tilde gets us, just to be clear). Then, the number is ANDed with the mask for the final result
// To clear all bits from the most significant bit through i (inclusive), we do:
int clearMSBthroughI(int num, int i) {
int mask = (1 << i) - 1;
return num & mask;
}
Take the example of i = 3
1<<3 gives you 0x00001000
(1<<3)-1 gives you 0x00000111
num & (1<<i)-1 will clear the bits from msb to i
// To clear all bits from i through 0 (inclusive), we do:
int clearBitsIthrough0(int num, int i) {
int mask = ~(((1 << (i+1)) - 1);
return num & mask;
}
same example of i = 3 gives you
1 <<(3+1) =0x00010000
1 <<(3+1)-1 = 0x00001111
mask =~(1<<(3+1)-1) = 0x11110000
num & mask will cleaR the bits from 0 throuh i

How do I check if an integer is even or odd using bitwise operators

How do I check if an integer is even or odd using bitwise operators
Consider what being "even" and "odd" means in "bit" terms. Since binary integer data is stored with bits indicating multiples of 2, the lowest-order bit will correspond to 20, which is of course 1, while all of the other bits will correspond to multiples of 2 (21 = 2, 22 = 4, etc.). Gratuituous ASCII art:
NNNNNNNN
||||||||
|||||||+−− bit 0, value = 1 (20)
||||||+−−− bit 1, value = 2 (21)
|||||+−−−− bit 2, value = 4 (22)
||||+−−−−− bit 3, value = 8 (23)
|||+−−−−−− bit 4, value = 16 (24)
||+−−−−−−− bit 5, value = 32 (25)
|+−−−−−−−− bit 6, value = 64 (26)
+−−−−−−−−− bit 7 (highest order bit), value = 128 (27) for unsigned numbers,
value = -128 (-27) for signed numbers (2's complement)
I've only shown 8 bits there, but you get the idea.
So you can tell whether an integer is even or odd by looking only at the lowest-order bit: If it's set, the number is odd. If not, it's even. You don't care about the other bits because they all denote multiples of 2, and so they can't make the value odd.
The way you look at that bit is by using the AND operator of your language. In C and many other languages syntactically derived from B (yes, B), that operator is &. In BASICs, it's usually And. You take your integer, AND it with 1 (which is a number with only the lowest-order bit set), and if the result is not equal to 0, the bit was set.
I'm intentionally not actually giving the code here, not only because I don't know what language you're using, but because you marked the question "homework." :-)
In C (and most C-like languages)
if (number & 1) {
// It's odd
}
if (number & 1)
number is odd
else // (number & 1) == 0
number is even
For example, let's take integer 25, which is odd.
In binary 25 is 00011001. Notice that the least significant bit b0 is 1.
00011001
00000001 (00000001 is 1 in binary)
&
--------
00000001
Just a footnote to Jim's answer.
In C#, unlike C, bitwise AND returns the resulting number, so you'd want to write:
if ((number & 1) == 1) {
// It's odd
}
if(x & 1) // '&' is a bit-wise AND operator
printf("%d is ODD\n", x);
else
printf("%d is EVEN\n", x);
Examples:
For 9:
9 -> 1 0 0 1
1 -> & 0 0 0 1
-------------------
result-> 0 0 0 1
So 9 AND 1 gives us 1, as the right most bit of every odd number is 1.
For 14:
14 -> 1 1 1 0
1 -> & 0 0 0 1
------------------
result-> 0 0 0 0
So 14 AND 1 gives us 0, as the right most bit of every even number is 0.
Also in Java you will have to use if((number&1)==1){//then odd}, because in Java and C# like languages the int is not casted to boolean. You'll have to use the relational operators to return
a boolean value i.e true and false unlike C and C++ like languages which treats non-zero value as true.
You can do it simply using bitwise AND & operator.
if(num & 1)
{
//I am odd number.
}
Read more over here - Checking even odd using bitwise operator in C
Check Number is Even or Odd using XOR Operator
Number = 11
1011 - 11 in Binary Format
^ 0001 - 1 in Binary Format
----
1010 - 10 in Binary Format
Number = 14
1110 - 14 in Binary Format
^ 0001 - 1 in Binary Format
----
1111 - 15 in Binary Format
AS It can observe XOR Of a number with 1, increments it by 1 if it is
even, decrements it by 1 if it is odd.
Code:
if((n^1) == (n+1))
cout<<"even\n";
else
cout<<"odd\n";
#include <iostream>
#include <algorithm>
#include <vector>
void BitConvert(int num, std::vector<int> &array){
while (num > 0){
array.push_back(num % 2);
num = num / 2;
}
}
void CheckEven(int num){
std::vector<int> array;
BitConvert(num, array);
if (array[0] == 0)
std::cout << "Number is even";
else
std::cout << "Number is odd";
}
int main(){
int num;
std::cout << "Enter a number:";
std::cin >> num;
CheckEven(num);
std::cout << std::endl;
return 0;
}
In Java,
if((num & 1)==0){
//its an even num
}
//otherwise its an odd num
This is an old question, however the other answers have left this out.
In addition to using num & 1, you can also use num | 1 > num.
This works because if a number is odd, the resulting value will be the same since the original value num will have started with the ones bit set, however if the original value num was even, the ones bit won't have been set, so changing it to a 1 will make the new value greater by one.
Approach 1: Short and no need for explicit comparison with 1
if (number & 1) {
// number is odd
}
else {
// number is even
}
Approach 2: Needs an extra bracket and explicit comparison with 0
if((num & 1) == 0){ // Note: Bracket is MUST around num & 1
// number is even
}
else {
// number is odd
}
What would happen if I miss the bracket in the above code
if(num & 1 == 0) { } // wrong way of checking even or not!!
becomes
if(num & (1 == 0)) { } // == is higher precedence than &
https://en.cppreference.com/w/cpp/language/operator_precedence

How to go through each bit of a byte

I do not not know how to implement the following algorithm.
For example I have int=26, this is "11010" in binary.
Now I need to implement one operation for 1, another for 0, from left to right, till the end of byte.
But I really have no idea how to implement this.
Maybe I can convert binary to char array, but I do not know how.
btw, int equals 26 only in the example, in the application it will be random.
Since you want to move from 'left to right':
unsigned char val = 26; // or whatever
unsigned int mask;
for (mask = 0x80; mask != 0; mask >>= 1) {
if (val & mask) {
// bit is 1
}
else {
// bit is 0
}
}
The for loop just walks thorough each bit in a byte, from the most significant bit to the least.
I use this option:
isBitSet = ((bits & 1) == 1);
bits = bits >> 1
I find the answer also in stackoverflow:
How do I properly loop through and print bits of an Int, Long, Float, or BigInteger?
You can use modulo arithmetic or bitmasking to get what you need.
Modulo arithmetic:
int x = 0b100101;
// First bit
(x >> 0) % 2; // 1
// Second bit
(x >> 1) % 2; // 0
// Third bit
(x >> 2) % 2; // 1
...
etc.
Bitmasking
int x = 0b100101;
int mask = 0x01;
// First bit
((mask << 0) & x) ? 1 : 0
// Second bit
((mask << 1) & x) ? 1 : 0
...
etc.
In C, C++, and similarly-syntaxed languages, you can determine if the right-most bit in an integer i is 1 or 0 by examining whether i & 1 is nonzero or zero. (Note that that's a single & signifying a bitwise AND operation, not a && signifying logical AND.) For the second-to-the-right bit, you check i & 2; for the third you check i & 4, and so on by powers of two.
More generally, to determine if the bit that's jth from the right is zero, you can check whether i & (1 << (j-1)) != 0. The << indicates a left-shift; 1 << (j-1) is essentially equivalent to 2j-1.
Thus, for a 32-bit integer, your loop would look something like this:
unsigned int i = 26; /* Replace this with however it's actually defined. */
int j;
for (j = 31; j >= 0; j--)
{
if ((i & (1 << (j-1))) != 0)
/* do something for jth bit is 1 */
else
/* do something for jth bit is 0 */
}
Hopefully, that's enough to get you started.
Came across a similar problem so thought I'd share my solution. This is assuming your value is always one byte (8 bits)
Iterate over all 8 bits within the byte and check if that bit is set (you can do this by shifting the bit we are checking to the LSB position and masking it with 0x01)
int value = 26;
for (int i = 0; i < 8; i++) {
if ((value >> i) & 0x01) {
// Bit i is 1
printf("%d is set\n", i);
}
else {
// Bit i is 0
printf("%d is cleared\n", i);
}
}
I'm not exactly sure what you say you want to do. You could probably use bitmasks to do any bit-manipulation in your byte, if that helps.
Hi
Look up bit shifting and bitwise and.

Swap two bits with a single operation in C?

Let's say I have a byte with six unknown values:
???1?0??
and I want to swap bits 2 and 4 (without changing any of the ? values):
???0?1??
But how would I do this in one operation in C?
I'm performing this operation thousands of times per second on a microcontroller so performance is the top priority.
It would be fine to "toggle" these bits. Even though this is not the same as swapping the bits, toggling would work fine for my purposes.
Try:
x ^= 0x14;
That toggles both bits. It's a little bit unclear in question as you first mention swap and then give a toggle example. Anyway, to swap the bits:
x = precomputed_lookup [x];
where precomputed_lookup is a 256 byte array, could be the fastest way, it depends on the memory speed relative to the processor speed. Otherwise, it's:
x = (x & ~0x14) | ((x & 0x10) >> 2) | ((x & 0x04) << 2);
EDIT: Some more information about toggling bits.
When you xor (^) two integer values together, the xor is performed at the bit level, like this:
for each (bit in value 1 and value 2)
result bit = value 1 bit xor value 2 bit
so that bit 0 of the first value is xor'ed with bit 0 of the second value, bit 1 with bit 1 and so on. The xor operation doesn't affect the other bits in the value. In effect, it's a parallel bit xor on many bits.
Looking at the truth table for xor, you will see that xor'ing a bit with the value '1' effectively toggles the bit.
a b a^b
0 0 0
0 1 1
1 0 1
1 1 0
So, to toggle bits 1 and 3, write a binary number with a one where you want the bit to toggle and a zero where you want to leave the value unchanged:
00001010
convert to hex: 0x0a. You can toggle as many bits as you want:
0x39 = 00111001
will toggle bits 0, 3, 4 and 5
You cannot "swap" two bits (i.e. the bits change places, not value) in a single instruction using bit-fiddling.
The optimum approach if you want to really swap them is probably a lookup table. This holds true for many 'awkward' transformations.
BYTE lookup[256] = {/* left this to your imagination */};
for (/*all my data values */)
newValue = lookup[oldValue];
The following method is NOT a single C instruction, it's just another bit fiddling method. The method was simplified from Swapping individual bits with XOR.
As stated in Roddy's answer, a lookup table would be best. I only suggest this in case you didn't want to use one. This will indeed swap bits also, not just toggle (that is, whatever is in bit 2 will be in 4 and vice versa).
b: your original value - ???1?0?? for instance
x: just a temp
r: the result
x = ((b >> 2) ^ (b >> 4)) & 0x01
r = b ^ ((x << 2) | (x << 4))
Quick explanation: get the two bits you want to look at and XOR them, store the value to x. By shifting this value back to bits 2 and 4 (and OR'ing together) you get a mask that when XORed back with b will swap your two original bits. The table below shows all possible cases.
bit2: 0 1 0 1
bit4: 0 0 1 1
x : 0 1 1 0 <-- Low bit of x only in this case
r2 : 0 0 1 1
r4 : 0 1 0 1
I did not fully test this, but for the few cases I tried quickly it seemed to work.
This might not be optimized, but it should work:
unsigned char bit_swap(unsigned char n, unsigned char pos1, unsigned char pos2)
{
unsigned char mask1 = 0x01 << pos1;
unsigned char mask2 = 0x01 << pos2;
if ( !((n & mask1) != (n & mask2)) )
n ^= (mask1 | mask2);
return n;
}
The function below will swap bits 2 and 4. You can use this to precompute a lookup table, if necessary (so that swapping becomes a single operation):
unsigned char swap24(unsigned char bytein) {
unsigned char mask2 = ( bytein & 0x04 ) << 2;
unsigned char mask4 = ( bytein & 0x10 ) >> 2;
unsigned char mask = mask2 | mask4 ;
return ( bytein & 0xeb ) | mask;
}
I wrote each operation on a separate line to make it clearer.
void swap_bits(uint32_t& n, int a, int b) {
bool r = (n & (1 << a)) != 0;
bool s = (n & (1 << b)) != 0;
if(r != s) {
if(r) {
n |= (1 << b);
n &= ~(1 << a);
}
else {
n &= ~(1 << b);
n |= (1 << a);
}
}
}
n is the integer you want to be swapped in, a and b are the positions (indexes) of the bits you want to be swapped, counting from the less significant bit and starting from zero.
Using your example (n = ???1?0??), you'd call the function as follows:
swap_bits(n, 2, 4);
Rationale: you only need to swap the bits if they are different (that's why r != s). In this case, one of them is 1 and the other is 0. After that, just notice you want to do exactly one bit set operation and one bit clear operation.
Say your value is x i.e, x=???1?0??
The two bits can be toggled by this operation:
x = x ^ ((1<<2) | (1<<4));
#include<stdio.h>
void printb(char x) {
int i;
for(i =7;i>=0;i--)
printf("%d",(1 & (x >> i)));
printf("\n");
}
int swapb(char c, int p, int q) {
if( !((c & (1 << p)) >> p) ^ ((c & (1 << q)) >> q) )
printf("bits are not same will not be swaped\n");
else {
c = c ^ (1 << p);
c = c ^ (1 << q);
}
return c;
}
int main()
{
char c = 10;
printb(c);
c = swapb(c, 3, 1);
printb(c);
return 0;
}

Resources