Friday, 19 August 2022

Mid year 2022 and Things I need to change

 Its been a rather different 1st half of 2022 with so many things revolving around with so many life lessons about relationship management, knowing people, unravelling of peoples attitude, knowing what is needed in life, what are the priorities . I inted to document a lof of these and the impact it has had on me. A lot of these seem to have made me into a different person. I intend to keep a few changes and try and modify a few . This post is identifying those and keeping a journal on the same.

1. Anger

2. Shaky Relationships

3. swimming in the murky waters

4. Leadership

5. Sacrifices

6. Results and its relevance in the longterm

7. Physical Health

8. Mental Health

9. Relationship with wife 

10. Relationship with kids

11. Relationship with work

12 Relationship with Self

Life Goals

 This is about the Goals I intend to achieve in my lifetime and the timeline within which I intend to achieve

Akshay Wedding and my learnings

 This post is about Akshay wedding and my involvement and how did i think things went. Also i intend to keep a journal on what do i feel about things.

Things I need to do - Aug 2022

 I am not on top of my career. I have fallen behind in my career goals, in the accumulation of knowledge.

I seem to have taken it a little too easy in past 6-8 months. Its about time, I start focussing on the important stuff to get my self back into reckoning. I will be focussing on the following things - 

Daily : 

1. Read 5G Spec (38.211, 212, 213,214,215,141,104,331,etc.,)

2. Read 5G NR Codebase (95N, 105, FlexRAN)

3. Discuss with subject experts (for eg: Principal engineers)

4. Build a reputation as a technical expert


Weekly : 

1. Spend time on weekends learning about changes in industry. by talking to people in Radisys, EdgeQ, Nokia, Qualcomm, Apple etc.,

2. Spend time in refining career aspirations

3. Improve gaps in skillsets

4. Build on my strengths

I will be reviewing the same at the end of the year.

AY-2022 Mid Year Review

 Review of how do I fare w.r.t my own expectations in 2022

Thursday, 28 April 2022

The choice of Relationships for Future

Man is a social being, Every Man/Woman needs that social connect to feel wanted, to feel they belong to the place, to have a sense of pride, to have a sense of social security, to feel being part of a community. While the above may seem altruistic expectation to have in life, most will end up not getting most of the above things. Given this how do we navigate our future, Given that all these notions are part of life for as long as we are alive, Can we think through and be a little more systematic about these rather acting in random or in the spur of the moment ?? Can we search our own thoughts and with all the learnings from our/others life experiences, can we formulate an approach for ourselves which (we believe) will hold us in good stead?? This is my attempt at the rumblings within my mind to search my own answers - 

The Trigger

 This week I got 3 invitations for a not so major but few important functions. One from  a once close cousins kids 1st year birthday (Infact its my parents who got the invite and my name was added as a add-on), my wife's cousins son naming ceremony and my wife's another cousin daughters naming ceremony. while the first one is in Bangalore the other two functions are about 400km from here. The 1st year birthday function is about 3 days away where as the naming ceremony is about 16-17 days away. With the receival of the invitations it got me thinking as to which one to attend and which ones not to attend. 

Dilemma

It started a thread of thoughts in my mind, as to how do i want to handle such things in future. While I as a person likes to meet people, especially the ones who i happen to know from a long time. Infact my personal goal is "To have close and rewarding relationships with all the important people in my life". Being surrounded by people is one of the common elements of the future that I have envisioned for me and my family. At the same breath let me not forget to add the emotional treachery I was meted out particularly from the relatives all throughout my life. While the emotional treachery at every important phase of my life in itself can be a separate topic of its own and a blog for some other day, it spawned a new thread of thoughts in my mind as to how do I go about all the relationships in my life. Do I want to endure this emotional treachery and develop the magnanimity and hope that people turn out better in the future or just develop thick skin and be indifferent to the actions of every body? Should I just start ignoring such people and start focusing inward and on people who happen to be nice and good to me. ?? Should I just behave in a way whatever my mind think its best at that particular moment? Should I just ignore all this and just follow the herd and not have any opinion on this?? While all these may sound simple while looking at them as separate entities, but they are interrelated and a lot of it will depend on how future shapes up. While a lot of people may be okay with just choosing the path of least resistance, it may not be the thing of interest to people with a strong conscience. Also choosing a path gets further complicated, when one knows that they dont have the support of their immediate family (of wife, parents, siblings). Do I want to take into account how my brother, parents, wife would behave to the same scenario. How much cost (Time, emotional, Money in the exact order of importance) am I willing to bear for such events?

Way forward

As I reflect on whom to chose & invest time and whom not to invest time and energy. This seems to be common though conundrum which i have to go through anytime there is a small/large gathering of people where my old adversaries are about to come or if they are hosting the functions. I m beginning to think maybe i need to settle down on a template for life.  A new template which i can refer to anytime in future i end up facing this di-elemma.  I tried discuss this with my wife from past 4 days and tried to explain my dielemma but she doesnt seem to give a damn about this. She seems busy in her own things with little to no interest and listening to whatever I had to say. So left to fend for myself, I m turning to do things that I know i.,e put down all the thoughts into a blog and help it become your guide. As it started thinking more, I narrowed down on two approaches.

Option 1 :

    Attend functions of only the small set of close relationships and ignore all the rest.

Option 2

    Attend all functions of every tom dick and harry as long as I/my parents get the invite without giving any further thought. Attend for the sake of building more people in our life.

Evaluate

Option 1: Attend functions of only the small set of close relationships and ignore all the rest.

    Pros :  a. Peace of mind in the form of not faking any relationship (while fully ackowledging that its a difficult thing to know who is faking or not OR even worse who wasnt faking before but have started faking now). b. Peace of mind in being only surrounded by only people with whom you can resonate at that point of time our lives. c. Less people, Less managing emotions, Less chaos. d. Construct a life by being surrounded with real people and real relationships. 

    Cons : Given that i dont have even a single person from my dads family and ever decreasing number of treacherous, selfish people from my Moms family there is a real possibility that in the future I and my kids may end up with very few people in our lives. This is especially important given that my wife is hell bent on showing off status, showing of the number of people in our lives to her relatives and feel the constant superiority at every stage of life.  This may also weaken me and my position within my immediate family in the long term given that my kids may start wondering as to why there is no one in their paternal family who shares a warm relationship. Also my wife seems to be averse to this option for the reasons mentioned above.

Option 2: Attend all functions of every tom dick and harry as long as I/my parents get the invite without giving any further thought.

    Pros  : a. It gives an illusion of being surrounded by a lot of people all the time. b. Attending multiple functions, attending to more people will improve the general understanding of people c. Increased network of people. especially the people who arent extended family but may have done things which are worthy of learning. d. Social Status which we get by the virtue of knowing a lot of people. e. It is increasing becoming apparent to me what my brother, my father , mother and to an extent my wife is inclined to. They are all people who just wants to go along whereever the wind is blowing without giving a shit about history. Recency effect dominates. OR the assumed quid pro quo feelings OR the path of least resistance. So going against all my inner familys opinion to honor or act as per my conscience may have repercussions within my family life.

    Cons : I may have to sacrifice my self respect and swallow a lot of hard feelings and try hard to forget all the misgivings, backstabbing, back bitching, and all the negativity people spread about my family. People will never be made answerable to all their past actions/behaviors. Everything..every insult will be brushed under the carpet. (under the garbage of "Need to move on with time"

Conclude : 

Given the current circumstances, it seems I may be leaning towards Option 2. But let me revisit this a little later with more perspectives and offer a final conclusion.

Thursday, 21 April 2022

The Kind of Dad I want to be

Hi Today is 21-April-2022 i.e., exactly 19 months and 9 days after I became a father. I m still over the moon when I hear my son Aarav calls me "Appa" and it sets off the adrenaline in me to entertain him as much as I possibly can. Over the past few weeks, I have been contemplating to write a post to jot down what kind of dad do I want to grow up into. I hope the below points serve me as a reminder or a guiding compass when things become rough (as they always gets in life ). 

1. I intend to grow into a father who ensures the human values are drilled into the kids and oversee that they understand the importance and practice it in their daily lives. while the list of human values are vast - some of the major ones - humility, treating everyone with respect, valuing relationships over materialistic things, always lead life a life of dignity, treat elders with love and affection, never hurt any organism, Be a vegetarian for life, Lead a life worth living, Be a benchmark of kindness, goodness...

2. My dream for my kids is to make them become "Good human beings" with universal values.

3. I intend to never physically hurt or yell at my kids over any of my frustrations or frustrations brought about by kids behaviors. I must remind myself to not become a father who supports and pampers their kids even when they are not on the right path. (As a reminder to myself - I intend to renew a vow on every mahaveer jayanthi to ensure this happens)

4. I wish they could learn the lessons i got to learn from the parents about the value of money, relationships, spirituality. Although the circumstances have changed, i wish i could make them understand the lessons without them having to traverse the same path/circumstances as i did.

5. I wish to become a source of strength and support in their life. I wish to offer them unconditional support and love till my last breadth. (like my parents are to me)

6. I wish to be their "biggest fan" forever. (Like my parents are to me)

7. I wish to make them learn discipline, good behavior without having to be angry.

8. I wish to be their friend in studies, take my time out to ensure my kids become best at what they want to excel. (Although, its my dream to see them become important persons in society like  - IAS, Doctors etc., I do not want to impose any of my dreams on my kids)

9. I wish to pursue a financial plan to enable my kids to have the freedom to choose education, a career (and pace) of their choice without having to think/worry about finances.

10. I wish to submit my ego, desires, self-righteousness in front of my kids to enable them grow into individuals that i (and in turn they) can be proud of.

Saturday, 29 January 2022

C Interview question weblinks

 This post is a collection of all the relevant/important articles i came across during my interview preparation. Since the available material is online and created by other, i have gracefully collected them purely for my future reference. All credits in creating those articles belong the original content creator


1. https://www.geeksforgeeks.org/bit-tricks-competitive-programming/

2. https://www.geeksforgeeks.org/bitwise-hacks-for-competitive-programming/

3. https://www.geeksforgeeks.org/bitwise-hacks-for-competitive-programming/




Tuesday, 4 January 2022

2021 : Annual Review

 At the beginning of 2021, I had set a few goals for myself, and naturally at the end of the year I evaluated myself against goals to see how do i fare. Overall this year I was at 58% completion by the end of the year with notable exceptions in completion of health, learning goals. Here i present a consolidated gist of my review

C Interview questions on bitwise operators

 

Q) Compute the sign of an integer?

The MSB bit of a number defines their sign. If the MSB bit is set, the number will be negative.

#include <stdio.h>
int main()
{
int sign = 0;
int data = 0;
printf("Enter the number\n");
scanf("%d",&data); //Get the number
sign = (data > 0) - (data < 0); // check the sign of the number
if(sign == 1)
{
printf("Enter number is a positve number\n");
}
else if(sign == -1)
{
printf("Enter number is a negative number\n");
}
else
{
printf("Enter number is zero\n");
}
return 0;
}

 

Q) Detect if two integers have opposite signs?

The two integers have different signs if their MSB (bit) is different. Using the EX-OR operator, we can check the sign of the integers.

We know that for the same input EX-OR produces the low output and for the different input it produces the high output.

E.g.

              BIT1               BIT2 BIT1  ^  BIT2
                1                  1                      0
                0                  0                      0
                1                  0                      1
                0                  1                      1

Let the given integers are “a” and “b”. The EX-OR of sign bit (MSB) of “a” and “b” will be 1 if the MSB of “a” and “b” is different. In other words, we can say, EX-OR of “a” and “b” will be negative if “a” and “b” have the opposite signs.

#include<stdbool.h>
#include<stdio.h>
bool CheckOppositeSign(int a, int b)
{
bool bRetValue = 0;
bRetValue = ((a ^ b) < 0); // 1 if a and b have opposite signs
return bRetValue;
}
int main()
{
int a = 0,b=0;
bool bRetValue;
//ENTER THE VALUE OF a & b
printf("Enter the Value of a = ");
scanf("%d",&a);
printf("\nEnter the Value of b = ");
scanf("%d",&b);
bRetValue = CheckOppositeSign(a, b); // check signs of a & b
if (true == bRetValue)
{
printf ("\nIntegers have the opposite sign\n\n");
}
else
{
printf ("\nInteger have the same sign\n\n");
}
return 0;
}

 

 

Q) Write a program to check an integer is a power of 2?

Here, I am writing a small algorithm to check the power of 2. If a number is a power of 2, the flag will be 1.

#include <stdio.h>
int main()
{
int flag = 0;
int data = 0;
printf("Enter the number ");
scanf("%d",&data); //Get the number
flag = ((data != 0) && !(data & (data - 1))); // check the power of 2
if(flag == 1)
{
printf("Number is a power of 2 \n");
}
else
{
printf("Enter number is not power of 2 \n");
}
return 0;
}

 

 

Note: Here I assume that bit of register starts with 0th position, it means the 2nd position is actually 3rd bits.

D7D6D5D4D3D2D1D0

Q) How to set a particular bit in C?

Setting a Bits

Bitwise OR operator (|) use to set a bit of integral data type.”OR” of two bits is always one if any one of them is one.

An algorithm to set the bits

Number  | =  (1<< nth Position)

A simple program to set a bit:

 

#include <stdio.h>
int main(int argc, char *argv[])
{
unsigned char cData=0x00;
int iPos =0;
printf("cData = 0x%x\n\n",cData);
printf("Enter the position which you want set = ");
scanf("%d",&iPos);
//Set the nth bit.
cData|=1<<iPos;
//Print the data
printf("\n\n%dth Bit Set Now cData will be = 0x%x\n",iPos,cData);
return 0;
}

 

 

Q) How to clear a particular bit in C?

Bitwise AND operator (&) use to clear a bit of integral data type. “AND” of two bits is always zero if any one of them is zero.

An algorithm to clear the bits

Number  &=  ~ (1<< nth Position)
To clear the nth bit, first, you need to invert the string of bits then AND it with the number.

A simple program to clear a bit:

 

#include <stdio.h>
int main(int argc, char *argv[])
{
unsigned char cData=0xFF;
int iPos =0;
printf("Initially cData = 0x%x\n\n",cData);
printf("Enter the position which you want clear = ");
scanf("%d",&iPos);
//clear the nth bit.
cData &= ~(1<<iPos);
//Print the data
printf("\n\n%dth Bit clear Now cData will be = 0x%x\n",iPos,cData);
return 0;
}

 

Q) How to check if a particular bit is set in C?

To check the nth bit, shift the ‘1’ nth position toward the left and then “AND” it with the number.

An algorithm to check the bits

 Bit = Number & (1 << nth)

 

A simple program to check a bit:

 

#include <stdio.h>
int main(int argc, char *argv[])
{
unsigned char cData=0xFc;
int iPos =0;
printf("Initially cData = 0x%x\n\n",cData);
printf("Enter the position which you want check = ");
scanf("%d",&iPos);
if(cData & (1<<iPos)) //Check bit set or not
{
printf("\n\nBit is One\n");
}
else
{
printf("\n\nBit is zero\n");
}
return 0;
}

 

 

Q) How to toggle a particular bit in C?

Bitwise XOR (^) operator use to toggle the bit of an integral data type. To toggle the nth bit shift the ‘1’ nth position toward the left and “XOR” it.

An algorithm to toggle the bits

Number  ^=  (1<< nth Position)

 

A simple program to toggle a bit:

 

#include <stdio.h>
int main(int argc, char *argv[])
{
unsigned char cData=0xF8;
int iPos =0;
printf("Initially cData = 0x%x\n\n",cData);
printf("Enter the position which you want toggle = ");
scanf("%d",&iPos);
//toggle the nth bit.
cData ^= 1<<iPos;
//Print the data
printf("\n\n%dth Bit Set Now cData will be = 0x%x\n",iPos,cData);
return 0;
}

 

 

Q) Write an Efficient C Program to Reverse Bits of a Number?

There are a lot of ways to reverse the bits of a number, here I am describing three general methods to reverse the bits.

Method 1:

In this method, we will check the set bits of num and run the loop through all the bits of an integer. If we find the ith bits of num is set then just put 1 at the ((INT_BITS – 1) – ith ) position of tmp, where INT_BITS is the number of bits of an integer.

#define CHAR_BITS 8 // size of character
#define INT_BITS ( sizeof(int) * CHAR_BITS)
//bit reversal function
unsigned int ReverseTheBits(unsigned int num)
{
unsigned int iLoop = 0;
unsigned int tmp = 0; // Assign num to the tmp
int iNumberLopp = INT_BITS;
for(; iLoop < iNumberLopp; ++iLoop)
{
if((num & (1 << iLoop))) // check set bits of num
{
tmp |= 1 << ((INT_BITS - 1) - iLoop); //putting the set bits of num in tmp
}
}
return tmp;
}

 

 

Method 2:

It is a simple algorithm to reverse bits of the 32-bit integer. This algorithm uses the eight constant value for reversing the bits and takes five simple steps.

In the below section, I am describing the functioning of each step.

Steps 1:
num = (((num & 0xaaaaaaaa) >> 1) | ((num & 0x55555555) << 1));

This expression used to swap the bits.
Let an example, suppose num is 0100, after the above expression it will be 1000.

Steps 2:
num = (((num & 0xcccccccc) >> 2) | ((num & 0x33333333) << 2));

Above expression uses to swap the 2 bits of a nibble. Suppose num is 10 00, after the above expression, it will be 00 01.

Steps 3:
num = (((num & 0xf0f0f0f0) >> 4) | ((num & 0x0f0f0f0f) << 4));

An expression used to swaps the nibbles. like if num is 0011 0010 then after the above expression it will be 0010 0011.

Steps 4:
num = (((num & 0xff00ff00) >> 8) | ((num & 0x00ff00ff) << 8));

This statement uses to swap the bytes of an integer. Let num is 00001000 00001100, after the above expression, it will be 00001100 00001000.

Steps 5:
((num >> 16) | (num << 16));

The above expression uses to swap the half-word of an integer. Means that if the num is 0000000011001110 1000100100000110 after the above result number will be 1000100100000110 0000000011001110.

//bit reversal function
unsigned int ReverseTheBits(register unsigned int x)
{
x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
return((x >> 16) | (x << 16));
}

 

Q) Write a program to count set bits in an integer?

There are a lot of ways to count the number of bits in a given integer, here I am writing two approaches naive and  Brian Kernighan’s.

In naive approach requires one iteration per bit until no more bits are set.

#include <stdio.h>
#define CHAR_BITS 8 // size of character
#define INT_BITS ( sizeof(int) * CHAR_BITS)
int main()
{
unsigned int CountSetBits = 0; //Total number of bit set.
unsigned int n = 0; //Variable that set bits you want to count
printf("Enter the Number ");
scanf("%d", &n);
while (n)
{
CountSetBits += n & 1;
n >>= 1;
}
printf("Number of 1 = %d", CountSetBits);
}

 

Brian Kernighan’s method goes through as many iterations as there are set bits.

1. Initialize CountSetBits = 0

2. If integer n is not zero.

( a ). Perform bitwise operation and assign the value back to the n.
These bitwise operations clear the least significant.
n &= (n – 1);

( b ). Increment CountSetBits by 1.

( c ). Again go to step 2.

3. If there are no set bits remaining then return CountSetBits.

#include <stdio.h>
#define CHAR_BITS 8 // size of character
#define INT_BITS ( sizeof(int) * CHAR_BITS)
int main()
{
unsigned int n = 0; //Variable that set bits you want to count
unsigned int CountSetBits = 0; //Total number of bit set
printf("Enter the Number ");
scanf("%d", &n);
while(n)
{
n &= (n - 1); // clear the least significant bit set
CountSetBits++;
}
printf("Number of 1 = %d", CountSetBits);
}

 

 

Q) Rotate bits of a number in C?

Like the assembly in C language, there is no operator to rotate the bits, so if we require rotating a bit, then we have to do it manually.

Basically, bit rotation is similar to the shift operation except that in shift operation the bits that fall off at one end are put back to the other end.

There are two types of rotation possible left and right. In the left rotation, the bits that fall off at the left end are put back at the right end and in the right rotation, the bits that fall off at the right end are put back at the left end.

Example:
If data is stored using 8 bits, then the left rotation of a data 32(‭‬00100000‬) by 2 becomes ‭128 (10000000). As similar to left rotation, if data is stored using 8 bits, then the right rotation of the data 32(‭‬00100000‬) by 2 becomes 8 (00001000).

#include <stdio.h>
#define INT_BITS 32
#define ROTATE_LEFT(pos, data) ((data << pos)|(data >> (INT_BITS - pos)))
#define ROTATE_RIGHT(pos, data) ((data >> pos)|(data << (INT_BITS - pos)))
int main()
{
int pos = 2; // Number of rotation
int data = 32; //data which will be rotate
printf("%d Rotate Left by %d is ", data, pos);
printf("%d \n", ROTATE_LEFT(pos, data));
printf("%d Rotate Right by %d is ",data, pos);
printf("%d \n", ROTATE_RIGHT(pos, data));
return 0;
}

 

 

Q) Compute the minimum (min) or maximum (max) of two integers without branching?

We can find the minimum (min) or maximum (max) number without the branching with the help of a bitwise operator.

Let’s assume “a” and “b” are integers numbers and “result” is another integer variable that contains the result of the
computation.

So to compute the minimum number we have to write the below expression.

result = b ^ ((a ^ b) & -(a < b)); // min(a, b)
In above expression,if a < b, then -( a < b) become -1, so it behave like below expression
result = b ^ ((a ^ b) & ~0);
result = b ^ a ^ b; // b^b is zero
result = a ^ 0; // oring with 0 does not effect
result = a; //minimum number

 

Compute the maximum number we have to write the below expression.

result = a ^ ((a ^ b) & -(a < b)); // max(a, b)
In above expression,if a > b, then -( a > b) become 0, so it behave like below expression
result = a ^ ((a ^ b) & -(0));
result = a ^ 0; // oring with 0 does not effect
result = a; //Maximum number

 

Q) Swap two numbers without using a temporary variable?

Using the EX-OR operator, we can swap two numbers. Here the concept is that EX-OR of two same numbers is zero.

#include <stdio.h>
void SwapTwoNumber(int *a, int *b)
{
if(*a == *b) // Check if the two addresses are same
return;
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int main()
{
int x = 10;
int y = 20;
SwapTwoNumber(&x, &y);
printf("x = %d and y = %d",x,y);
return 0;
}

 

Q) Clear all bits from MSB to the ith bit

Here I have supposed data is stored using 8 bits.

let’s assume the ith position is 2.

mask =(1 <<( i+1)); // give you 00001000

so now if we subtract 1 from the mask (mask = mask – 1), then we will get 00000111

Using the mask, now we can clear MSB to ith bits of data (15).

data = data & mask; // Now bits are clear

interview questions on bitwise operators in c

#include <stdio.h>
int main()
{
unsigned int mask = 0; // mask flag
unsigned int i = 2; // ith position till u want to clear the bits
unsigned int data = 15; //value of data
mask = (1 << (i+1)); //Shift 1 ith position
mask = mask -1 ; //give us 00000111
//Now clear all bits from msb to ith position
data = data & mask;
printf("data = %d\n", data);
return 0;
}

 

Q) Clear all bits from LSB to ith bit

To clear all bits of a data from LSB to the ith bit, we have to perform AND operation between data and mask (flag) having LSB to ith bit 0.

To create a mask, first left-shift 1 (i+1) times.

mask =(1 << (i+1)); // give you 00001000

Now if we minus 1 from that, all the bits from 0 to i become 1 and remaining bits become 0.

mask = mask – 1 ; // give you 00000111

After that perform complement operation on the mask, all the bits from 0 to i become 0 and remaining bits become 1.

mask = ~mask; //give you 11111000

Now just simply perform anding operation between mask and data to get the desired result.

data = data & mask; // Now bits are clear from LSB to ith position

tricky questions on bitwise operators in c

#include <stdio.h>
int main()
{
unsigned int mask = 0; // mask flag
unsigned int i = 2; // ith position till u want to clear the bits
unsigned int data = 15; //value of data
mask = (1 << (i+1)); //Shift 1 ith position
mask = mask -1 ; //give us 00000111
mask = ~mask; //give us 11111000
//Now clear all bits from msb to ith position
data = data & mask;
printf("data = %d\n", data);
return 0;
}

 

Q) Multiply a number by 2 using bitwise operation

Left shifting of a data (number) by 1 is equivalent to data*2. In data, every bit is a power of 2, with each shift we are increasing the value of each bit by a factor of 2.

#include <stdio.h>
int main()
{
unsigned int data = 15; //value of data
data = data << 1; // equivalent to data * 2
printf("data = %d\n", data);
return 0;
}

 

Q) Divide a number by 2 using bitwise operation

Right shifting of a data (number) by 1 is equivalent to data/2. In data, every bit is a power of 2, with each right shift we are reducing the value of each bit by a factor of 2.

#include <stdio.h>
int main()
{
unsigned int data = 16; //value of data
data = data >> 1; // equivalent to data/2
printf("data = %d\n", data);
return 0;
}

 

Q) Multiply a given Integer with 3.5 using bitwise operation

We know that multiplication is basically an addition, so we can multiply a given integer (data) with 3.5 using the following operation, (2 *data) + data + (data/2).

#include <stdio.h>
int main()
{
unsigned int data = 10; //value of data
data = (data<<1) + data + (data>>1);; // equivalent to data * 3.5
printf("data = %d\n", data);
return 0;
}

 

Q) How to change endianness?

In the below image, you can see the conversion.

Endianness Conversion

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
//Function to change the endianess
uint32_t ChangeEndianness(uint32_t u32Value)
{
uint32_t u32Result = 0;
u32Result |= (u32Value & 0x000000FF) << 24;
u32Result |= (u32Value & 0x0000FF00) << 8;
u32Result |= (u32Value & 0x00FF0000) >> 8;
u32Result |= (u32Value & 0xFF000000) >> 24;
return u32Result;
}
int main()
{
uint32_t u32CheckData = 0x11223344;
uint32_t u32ResultData =0;
u32ResultData = ChangeEndianness(u32CheckData); //swap the data
printf("0x%x\n",u32ResultData);
u32CheckData = u32ResultData;
u32ResultData = ChangeEndianness(u32CheckData);//again swap the data
printf("0x%x\n",u32ResultData);
return 0;
}

 

Q) Swap two nibbles of a byte

A nibble consists of four bits, sometime interviewer asked the question to swap the nibble of a byte. It is a very easy question, here << (left shift) and >> (right shift) operators are used to swap the nibble.

#include <stdio.h>
//Macro to swap nibbles
#define SWAP_NIBBLES(data) ((data & 0x0F)<<4 | (data & 0xF0)>>4)
int main()
{
unsigned char value = 0x23; //value in hex
printf("0x%x", SWAP_NIBBLES(value)); //print after swapping
return 0;
}

 

Q) How do I get a bit from an integer value in C?

To get the ith bit, perform Anding operation between the ith bit and 1 (1 << i) after that shift the result ith position in right using the right operation.

#include <stdio.h>
//Macro to Get bit from the given position
#define GET_BITS(data, pos) ((data & ( 1 << pos)) >> pos)
int main()
{
unsigned char value = 16; //value in hex 00010000
unsigned char position = 1;
printf("%d\n", GET_BITS(value,position)); //print gets value from the 1th position
position = 4;
printf("%d\n", GET_BITS(value,position)); //print gets value from 3rd position
return 0;
}

 

 

Q) Write the macros to set, clear, toggle and check the bit of a given integer.

 

See the below macro,

  • #define SET_BIT(value, pos) value |= (1U<< pos)
  • #define CLEAR_BIT(value, pos) value &= ~(1U<< pos)
  • #define TOGGLE_BIT(value, pos) value ^= (1U<< pos)
  • #define CHECK_BIT_IS_SET_OR_NOT(value, pos) value & (1U<< pos)

Let see an example to set the bit using the above macro,

#include <stdio.h>
#define SET_BIT(value, pos) value |= (1U<< pos)
int main()
{
//value
unsigned int value =0;
//bit position
unsigned int pos = 0;
printf("Enter the value\n");
scanf("%d",&value);
printf("Enter the position you want to Set\n");
scanf("%d",&pos);
SET_BIT(value,pos);
printf("\n\n%dth Bit Set Now value will be = 0x%x\n",pos,value);
return 0;
}

 

Output:

set bit

 

Q) Write MACRO to swap the bytes in 32bit Integer Variable.

I have already written this program in endianness conversion. But here I am creating a Macro for the same.

#include <stdio.h>
#include <inttypes.h>
#define SWAP_BYTES(u32Value) ((u32Value & 0x000000FF) << 24)\
|((u32Value & 0x0000FF00) << 8) \
|((u32Value & 0x00FF0000) >> 8) \
|((u32Value & 0xFF000000) >> 24)
int main()
{
uint32_t u32CheckData = 0x11223344;
uint32_t u32Result = 0;
u32Result = SWAP_BYTES(u32CheckData); //swap the data
printf("0x%x\n",u32Result);
return 0;
}

byte conversion in c

Q) Swap all odd and even bits

In the above question, you need to swap the even and odd bits. To accomplish the above task you need to first find the even and odd bits then shift these bits. See the below steps,

Let the input number is data (Assuming integer size is 4 bytes),

  1. Get all even bits of data by doing bitwise and (&) of data with 0xAAAAAAAA (data & 0xAAAAAAAA).
  2. Get all odd bits of data by doing bitwise and (&) of data with 0x55555555 (data & 0x55555555).
  3. Right shift all even bits ((data & 0xAAAAAAAA)>>1).
  4. Left shift all odd bits ((data & 0x55555555)<<1).
  5. Combine the value which gets from the left and right operation ((data & 0xAAAAAAAA)>>1 | (data & 0x55555555)<<1).

Example code,

#include <stdio.h>
int main()
{
int data = 2;
data = ((data & 0xAAAAAAAA)>>1 | (data & 0x55555555)<<1);
printf("%d",data);
return 0;
}

 

Q) Count number of bits to be flipped to convert A to B

In this question, you need to count flipped bits that require to convert A to B. To accomplish this task you need to find the number of bits that are different in A and B.

Suppose, A = 8, B = 7
Binary representation of A => 00001000
Binary representation of B => 00000111
Here we have to flip highlighted four bits of A
to make it B.

 

Algorithm

  1. Calculate XOR of A and B.With the help of XOR, we will discard the common bits and set the bits that are different in numbers A and B.
  2. Count the set bits of the above calculated XOR result.

Example code,

#include <stdio.h>
//function to calculate flipped bits
int CountFlippedBits(int A, int B)
{
int XorResult = 0;
int count = 0;
//Doing Ex-or
XorResult = (A ^ B);
//Count set bits
while (XorResult)
{
count += XorResult & 1;
XorResult >>= 1;
}
return count;
}
int main()
{
int A = 8;
int B = 7;
int ret = 0;
//Function return count of flipped bits
ret = CountFlippedBits(A,B);
printf("Flipped Bits = %d\n",ret);
return 0;
}

 

Output: Flipped Bits = 4