Modify the function my Int2Str to output strings in any base from 2 to 36 For ex
ID: 3790373 • Letter: M
Question
Modify the function my Int2Str to output strings in any base from 2 to 36 For example if the integer has value 23 and the base is 5, the string would be 43. void myIntB2Str (int num, int base, chartastirstring)//TODO: add your code here Write a function getBit (x i) that returns 1 i f the i-th bit in x is 1, and 0 if the i-th bit in x is 0, where 0 i 31. int get Bit (int x, int i)//TODO: add your code here Write the function setBit (x, i) that returns the value of x with the bit at index i set to a 1 where o i 31. All other bits in x should be left unchanged. int set Bit (int X int i)//TODO: add your code here Write the function clearBit (x i) that returns the value of x with the bit at index i set to a 0 where o i 31. All other bits in x should be left unchanged. int clear Bit (int x, int i)//TODO: add your code hereExplanation / Answer
#include<stdio.h>
void myIntB2Str(int num, int base, char* string){
int i = 0;
char temp[50];
char c;
if (num == 0){ // handle the case of 0
string[i++] = '0';
string[i++] = '';
return;
}
while (num > 0){
int val = num%base;
if (val<10){
c = '0' + val; // use number to represent remainder if value is less than 10
} else {
c = 'A' + (val - 10); //use alphabet to represent number greater than or equal 10
}
temp[i++] = c;
num = num/base;
}
for (int j=i-1, k=0; j>=0;j--,k++){ //reverse the number
string[k] = temp[j];
}
string[i] = ''; //add string end character
return;
}
int getBit(int x, int i){
int j = 0x80000000; // set variable with only first bit as 1 and rest 0
int k;
x = x<<i; // shift left operation such that required bit is positioned at first position
k = x&j; // bitwise and operation
if ( k!= 0)
return 1;
else
return 0;
}
int setBit(int x, int i){
int j = 0x80000000; //set a variable with only first position as 1 and rest 0
j = j>>i; //moving the 1 in the number i number of times
x = x|j; //setting bit in result using bitwise or operator
return x;
}
int clearBit(int x, int i){
int j = 0x7FFFFFFF; //Setting a number with only first bit as 0 and rest as 1
int k;
for(k = 0;k<i;k++)
{
j = j >> 1; //moving the position of 0 to right in j
j = j|0x80000000; //adding 1 to first position in j
}
x = x&j; //clearing the bit using bitwise and operator
return x;
}
int main()
{
char string[50];
myIntB2Str(100,30,string);
printf("Number to different base: %s ",string);
printf("Bit at the position: %d ", getBit(5,15));
printf("Setting a bit: %d ", setBit(4,15));
printf("Clearing a bit: %d", clearBit(5,15));
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.