While reading a book called "Let us C" I read that a function showbit() exists which can show you the bits of the number. There wasn't any special header file mentioned for it. Searched for it on the internet and didn't found anything useful. Is there such a function? I want this to print the binary of decimal numbers. Else please give me a replacement function. Thanks
All integers are actually in binary in your computer. Its just that it is turned into a string that is the decimal representation of that value when you try to print it using printf and "%d". If you want to know what it looks like in some other base (e.g. base 2 or binary), you either have to provide the proper printf format string if it exists (e.g. "%x" for hex) or just build that string yourself and print it out.
Here is some code that can build the string representation of an integer in any base in [2,36].
#include <stdio.h>
#include <string.h>
char digits[]="01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void reverse(char* start, char* end)
{
for(end--;start<end;start++,end--)
{
char t=*start;
*start=*end;
*end=t;
}
}
int base_change(int n, int base,char* buffer)
{
int pos=0;
if (base>strlen(digits))
return -1;
while(n)
{
buffer[pos]=digits[n%base];
n/=base;
pos++;
}
buffer[pos]='\0';
reverse(buffer,buffer+pos);
return 0;
}
int main()
{
char buffer[32];
int conv=base_change(1024,2,buffer);
if (conv==0) printf("%s\n",buffer);
return 0;
}
You can also try this snippet which uses bit-shifting:
EDIT: (I've made it more portable)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BITS_IN_BYTE 8
#define INTEGRAL_TYPE unsigned int
void showBits(INTEGRAL_TYPE x) {
int i;
static int intSizeInBits = sizeof(INTEGRAL_TYPE) * BITS_IN_BYTE;
static char symbol[2] = {'0','1'};
char * binary = (char*) malloc(intSizeInBits + 1);
memset(binary, 0, intSizeInBits + 1);
for (i=0; i< intSizeInBits; i++) {
binary[intSizeInBits-i-1] = symbol[(x>>i) & 0x01];
}
printf("%s\n", binary);
free(binary);
}
int main() {
showBits(8698513);
return 0;
}
HTH!
This is a very simple solution for printing the bits of an integer
int value = 14;
int n;
for (n=8*sizeof(int)-1;n>=0;n--) {
printf("%d",(value >>n)&1);
}
The book "Let Us C" doesn't define it as a built-in function. The showbits() function is defined in later part of the book as a complete user defined function as I personally went through it. This answer is to anyone who haven't reached that later part of the book and are stuck at the first appearance of the function in the book.
you need to look here
#downvoter It works fine in c also. You just need to reformat your code in c-style.
#include <stdlib.h>
#include <stdio.h>
int main()
{
char buffer[20];
int i = 3445;
_itoa( i, buffer, 2 );
printf("String of integer %d (radix 2): %s",i,buffer);
return 0;
}
*you need to save your file as .c in MSVC++ for _itoa() to work.*
this is the header file for showbits
void showbits(unsigned int x)
{
int i;
for(i=(sizeof(int)*5)-1; i>=0; i--)
(x&(1u<<i))?putchar('1'):putchar('0');
printf("\n");
}
No there is no pre built function and you do not need to include any specific header file.
You will have to provide implementation for function showbits(int).
#include <stdio.h>
void showbits(int);
int main()
{
int j,k;
for(j=0;j<=11;j++)
{
printf("\nBinary value of decimal %d is :",j);
showbits(j);
}
return 0;
}
showbits(int n){
int i,k,andmask;
for(i = 15;i>=0;i--){
andmask = 1<<i;
k = n & andmask;
k==0 ? printf("0"):printf("1");
}
}
If you want to print out the bits of a float, for example you could do something like:
float myFloat = 45.2;
for (int n=0;n<8*sizeof(float);n++) {
printf("%d",(myFloat>>n)&1);
}
Related
I need to read a word from main function and convert the characters in UCASE if the first character is LCASE and vice versa using the user defined function.I tried ways for returning the array from function but still I am lacking some core ideas. Please debug this program and explain the way it works.
#include <stdio.h>
#include <string.h>
int* low (char str)
{
int i;
for (i=1; i<strlen(str);i++)
{
if(str[i]<91)
{
str[i]=str[i]+32;
}
else
{
}
}
return &str;
}
int* high (char str[50])
{
int i;
for (i=0; i<strlen(str);i++)
{
if(str[i]>91)
{
str[i]=str[i]-32;
}
else
{
}
}
return &str;
}
void main()
{
char str[50];
char* strl;
printf("Enter any string....\n");
scanf("%s",str);
if (str[0]<91)
{
*strl=low(str);
}
else
{
*strl=high(str);
}
printf("Converted string is %s.",*strl);
}
There is already a problem here:
So if you are saying this code is perfect and you want us to debug it and explain how (on earth) this works, then here you go.
In function int* low (char str), you have if(str[i]<91). Thats a problem right there. str is a char received as an argument, and hence str[i] is a straight compile-time error.
Another one to deal with is the return statement.
You have a statement:
return &str;
which would return the address of str, which by the way is a char, whereas function low is supposed to return a pointer to an int.
The same is applicable to high function as well.
Suggestion: Leave aside this bad code and get a beginner level C programming book first. Read it and the try some codes out of it.
A few inputs for improvement: (Which you may not comprehend)
change
void main()
to
int main(void)
Why? Refer this legendary post: What should main() return in C and C++?
Secondly, int both functions you are using strlen() in loop which will always return a fixed value. So, instead of
for (i=0; i<strlen(str);i++)
I'd suggest,
size_t strlength = strlen(str);
for (i=0; i < strlength; i++)
You can try the code and method as below:
#include <stdio.h>
#include <string.h>
char* caseConverter (char *str)
{
int i;
for (i=0; i<strlen(str);i++)
{
if(str[i]>=65 && str[i]<=90)
{
str[i]=str[i]+32; //To lower case
}
else if((str[i]>=97 && str[i]<=122))
{
str[i]=str[i]-32; //To upper case
}
else
printf("%c is not an alphabet \n",str[i]);
}
return str;
}
void main()
{
char inputStr[50]= "Stubborn";
char* opStr= caseConverter(inputStr);
printf("Converted string is %s",opStr);
}
I am trying to code the printf function. The problem is that my code is getting very messy and I need some help to try to make it organized and working (hopefully). I have been told that I should use "array of function pointers" so I tried below (ft_print_it) as you can see but I do not know how to how to structure my code so that I can use a big array of function pointer to put every function like int_decimal_octal and friends. Can you help me on that? Where can I call them from?
Also, I realized the little function below (cast_in_short) is giving me the same result as printf if I write the output with my ft_putnbr. My second question is thus: Can I make my printf work with little functions like this? Thank you so much.
int cast_in_short(int truc)
{
truc = (short)truc;
return (truc);
}
/*
here in the main I noticed that I get the same behaviour
between my putnbr and printf thanks to my little function
cast_in_short. This is the kind of function I want to use
and put into an array of pointer of functions in order
to make my printf work
*/
int main()
{
int n = 32769;
n = cast_in_short(n);
ft_putnbr(n);
printf("\n");
return (0);
}
/* function to launch ft_print_it */
int ft_print_str_spec(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putstr(va_arg(ap, char *));
else
{
ft_nbzero(ap, flag, 0);
ft_putstr(va_arg(ap, char *));
}
return (1);
}
int ft_print_oct(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putnbr(decimal_octal((va_arg(ap, int))));
else
{
ft_nbzero(ap, flag, 1);
ft_putnbr(decimal_octal((va_arg(ap, int))));
}
return (1);
}
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
char *ft_strjoin2(char const *s1, char const c);
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
int decimal_octal(int n) /* Function to convert decimal to octal */
{
int rem;
int i;
int octal;
i = 1;
octal = 0;
while (n != 0)
{
rem = n % 8;
n /= 8;
octal += rem * i;
i *= 10;
}
return (octal);
}
I think the best way to organize your code to avoid the function like your "flag_code" is to use an array of structure. With structure that contain a char (corresponding to the flag) and a function pointer.
For example :
typedef struct fptr
{
char op;
int (*ptr)(va_list);
} fptr;
And instatiate it like that (with { 'flag', name of the corresponding function} ) :
fptr fptrs[]=
{
{ 's', ft_print_nb_spec },
{ 'S', ft_print_nb_up },
{ 0, NULL }
};
Then when you know have char after the % (the flag) you can do something like this :
int i = -1;
while (fptrs[++i].op != flag && fptrs[i].op != 0);
if (fptrs[i].op != 0)
{
fptrs[i].ptr();
}
For exemple if flag = 'S' the while loop will stop when i = 1 and when you call fptrs[1].ptr() you will call the corresponding function in the structure.
I think instead of making your code messy by using function pointers, because in the end you cannot specialize printf function without providing the format, in C there is no function overloading or template functions. My suggestion is to special printf function by type.
// print seperator
void p (int end)
{ printf(end?"\n":" "); }
// print decimal
void pi (long long n)
{ printf("%lld",n); }
// print unsigned
void pu (unsigned long long n)
{ printf("%llu",n); }
// print floating point
void pf (double n)
{ printf("%g",n); }
// print char
void pc (char n)
{ printf("%c",n); }
// print string
void ps (char* n)
{ printf("%s",n); }
Test try here
pi(999),p(0),pf(3.16),p(0),ps("test"),p(1);
Output
999 3.16 test
Another option
In theory you can define polymorphic print function in a struct, in case you can do something like this. I haven't tested this yet.
struct Node
{
enum NodeType {Long,Double,Char,String} type;
union {long l,double d,char c,char* s};
};
void p(Node* n)
{
switch (n->type)
{
case Node::NodeType::Long: printf("%ld", n->l);
case Node::NodeType::Double: printf("%g",n->d);
case Node::NodeType::Char: printf("%c",n->c);
case Node::NodeType::String: printf("%s",n->s);
}
}
I'm a beginner in C language. After reading the initial chapters of Ritchie's book, I wrote a program to generate random numbers and alphabets.
The program compiles fine with gcc. However on running it, it gives an error "Segmentation fault", which is incomprehensible to my limited knowledge. I'd be glad to understand what I've written wrong.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
long int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
long int genrandom(int mino,int maxo) {
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1);
return val;
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%s ,",text);
}
char letterize(int num) {
char letter='A'+num;
return letter;
}
printf("%s ,",text); is wrong - it says that text is a nul-terminated array of chars. Use
printf("%c ,", text);
instead to print your single char.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
int genrandom(int mino,int maxo) {//changed function return type to int
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1); //Be careful when you are using '/' operator with integers
return val; //returning int here why set return type to long int?
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%c ,",text);//Replace %s with %c
}
char letterize(int num) { //No bound checking on num eh?
char letter='A'+num;
return letter;
}
That's all I had to say. :)
Why use %s when text is char. You dont need a string type in the function. Just a char would do. Change in the function : void randAlph ()
printf("%s ,",text);
to
printf("%c ,", text);
First, my objective with this code: take in a sentence into a C string. Iterate through the sentence and see how many instances of a particular letter occur.
This code is working somewhat but not giving the right number? Not sure why:
#include <stdio.h>
#include <string.h>
int tracker=0;
int letterCount (char *sentence)
{
int s=strlen(sentence);
int i=0;
for (i=0; i<s; i++){
if (sentence[i]=='h') {
tracker++;
}
}
return tracker;
}
int main(int argc, const char * argv[])
{
char *string="Hi there, what's going on? How's it going?";
letterCount(string);
printf("this sentensce has %i H's", tracker);
return 0;
}
The output I'm getting:
this sentensce has 2 H's
Not quite right. Any ideas?
This is the correct code if you mean case insensitive H:
#include <stdio.h>
#include <string.h>
int tracker=0;
int letterCount (char *sentence)
{
int s=strlen(sentence);
int i=0;
for (i=0; i<s; i++){
if (sentence[i]=='h' || sentence[i]=='H') { //'h' is not the same as 'H'
tracker++;
}
}
return tracker;
}
int main(int argc, const char * argv[])
{
char *string="Hi there, what's going on? How's it going?";
letterCount(string);
printf("this sentensce has %i H's", tracker);
return 0;
}
You have just mispelled small and the capital letter in your code.
Remember, the C language is case sensitive!
Although your label talks about the number of Hs, your letterCount looks for hs instead -- and it looks to me like the input you've provided does have two instances of lower-case h, just as it says.
If you want to count them together, you might consider filtering each input with tolower or toupper before checking what you have.
That number looks correct to me: you have 2 'h' characters in that sentence. If you want to count the 'H' characters as well, then you need a separate check.
size_t letterCount(const char* sentence, char c)
{
size_t count = 0;
while(sentence)
{
count += (*sentence == c);
++sentence;
}
return count;
}
What do we see here?
You can't have negative count, so use an unsigned type like size_t
sentence shouldn't be modified, so it should be const
pass in the char you want to match
sentence is a pointer, if it is null you are done. Don't need to call strlen.
sentence is a pointer, the actual pointer is pass by value, so you can modify it (see the increment, no need to make an extra variable)
boolean operators return 1 or 0, so no need to use the if. (Although, I haven't looked at the assembly to see if an if branch or an add 0 is cheaper. YMMV)
i have the following problems in C programming.
I have an array of strings stored as words[10][50]. I want to extract each of the string from the array and then pass it on to another function. I tried on the following:
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int Check_Anagram(char*,char*);
void main()
{
char words[10][20];
int i;
int flag;
for(i=0;i<3;i++)
{
scanf("%s\n",words[i][20]);
}
for(i=1;i<10;i++)
{
flag = Check_Anagram(words[i][20],words[i-1][20]);
}
getch();
}
int Check_Anagram(char *a,char *b)
{
printf("%s %s\n",a,b);
return 1;
}
This creates an exception during compiling.
Now i think that when i use the "printf" statement then this nomenclature works fine i.i words[i] prints the string "i" from the double dimension words array. When i try to do the same thing with the check function then the error occurs.
Can soemone point me how to do this passing ?
P.S. Please ignore any error in efficiency of program and likewise. I need your help and this is just a test program at learning string passing to a function
Thanks
You're passing words[i][20]. You need to pass words[i] instead in both loops. Try this:
for(i = 1; i < 3; i++) /* i < 3 */
{
flag = Check_Anagram(words[i], words[i-1]);
}
Another problem is that you're reading 3 strings and trying to print 10. So when you pass words[3] it contains garbage: printf tries to print garbage which need not be 0-terminated.
In the first for loop, when i is 0, you're pointing to words[-1], that's your exception.
flag = Check_Anagram(words[i][20],words[i-1][20]);
You are passing the 21st letter of each word the Check_Anagram. Instead you should pass the words themselves:
flag = Check_Anagram(words[i],words[i-1]);
You have a similar problem where you use scanf. To read a line from the console to each word you would use:
for(i=0;i<10;i++)
{
scanf("%s\n",words[i]);
}
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int Check_Anagram(char [],char []);
void main()
{
char words[10][20];
int i;
int flag;
for(i=0;i<3;i++)
{
scanf("%s\n",words[i]);
}
for(i=1;i<10;i++)
{
flag = Check_Anagram(words[i],words[i-1]);
}
getch();
}
int Check_Anagram(char a[],char b[])
{
printf("%s %s\n",a,b);
return 1;
}
I finally got it corrected thanks to the help of all users.
I have posted the corrected code for people who are struggling with passing of string extracted from an array of strings to another function. hope it helps.