Header Ads

Embedded C Interview Questions with Answers | Part 7

How to Count Number of 1's in Given Number in C 

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

//Count number of one in given number

int fun_bitCount(int num)
{
char bitCount = 0;
int testBit = 0;
for(int j=1; j<num; j = j << 1)
{
testBit = num & j;
if(testBit)
{
bitCount++;
}
}

return bitCount;
}

int fun_bitCount_lastPos(int num)

{
char bitCount = 0;
int testBit = 0;
while(num > 0)
{
  if(num & 1)
  {
   bitCount++;
  }
  num = num >> 1;
}
return bitCount;
}

int fun_bitCount_firstPos(int num)

{

char bitCount = 0;

int testBit = 0;

while(num != 0)

{
  if(num & 0x8000)
  {
bitCount++;
}
  num = num << 1;
} 
return bitCount;

}


int main()

{

int bitTest = 0x7F00;
printf("bitCount based on bit check = %d\n", fun_bitCount(bitTest));
printf("bitCount based on last bit position = %d\n", fun_bitCount_lastPos(bitTest));
printf("bitCount based on first bit position = %d\n", fun_bitCount_firstPos(bitTest));

getch();
return 0;

}


OUTPUT:


bitCount = 7

bitCount based on last bit position = 7

bitCount based on first bit position = 7

How to Find Max & Min of Two Numbers without using Conditional Operator in C

#include "stdafx.h"
#include <stdio.h>
#include <conio.h>


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;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int x = 0xCCCC;  // we want to find the minimum of x and y
    int y = 0x7777;
    int r;  // the result goes here

    r = y ^ ((x ^ y) & -(x < y)); // min(x, y)
    printf("Min: %x\n",r);

    r = X ^ ((x ^ y) & -(x < y)); // max(x, y)
    printf("Max: %x\n",r);

    int ans1 = clearBitsIthrough0(0x77, 3);
    int ans2 = clearMSBthroughI(0xFF, 3);

    printf("Ans1: %x & Ans2 = %x\n",ans1, ans2);

    getch();
    return 0;
}


-----------------------------------

OUTPUT:

Min: 7777

Max: CCCC
Ans1: 70 & Ans2 = 7
-----------------------------------


How do I remove Space from Given String in C with example Code

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
char testString[] = "Kapil Thakar";
char *outString = (char *) malloc (sizeof(testString));
int i = 0;
for(i=0 ; i<strlen(testString); i++)
{

  if ( *(testString + i) != ' ')
  {
printf("%c" , *(outString + i) = *(testString + i));
  } 

}
printf("\n");

getch();
return 0;

}

OUTPUT:

KapilThakar