Hello fellow Programmers,
I might want to ask you ,
I`ve got a task from my University to convert a decimal digit (0-9) to a half bit (nibble = 0101 ie.) the restriction is that we cannot use if statements
so i tried a little bit and came so far
int main()
{
int n;
printf("type in your digit");
scanf("%d", &n );
printf("%n%n%n%n", (n/8)%2, (n/4)%2, (n/2)%2, n%2);
return 0;
}
My problem here is that i cant put in a digit if i do so the program crashes
im really struggling and dont know how to proceed or make it work
can you give me some examples of how it could work or some good advice how to make it work.
i would really appreciate it
Thank you really for any help and answer!
You're using the wrong format specifier to printf
.
The %n
format specifier expects an int *
and writes the number of characters written so far to the given memory address. Because you pass in a int
to an argument expecting an int *
, printf
interprets that number as a memory address and tries to write to it. This is undefined behavior, and will most likely result in a core dump.
You want to use %d
instead, is used to output an int
:
printf("%d%d%d%d", (n/8)%2, (n/4)%2, (n/2)%2, n%2);