How to print binary number as hexdecimal? - c

I have a binary number, and I need to print it as hexdecimal number. (its a function in a bigger project)
I made this function, but I was only able to print it in reverse.
this is the function:
int printOctalToHex (unsigned int octalNum) {
unsigned int binaryNum;
int temp;
int i = 1;
binaryNum = octalToBinary(octalNum);
while (1) {
temp = (binaryNum % 10000);
binaryNum = binaryNum / 10000;
if (temp == 0) {
printf("0");
}
if (temp == 1) {
printf("1");
}
if (temp == 10) {
printf("2");
}
if (temp == 11) {
printf("3");
}
if (temp == 100) {
printf("4");
}
if (temp == 101) {
printf("5");
}
if (temp == 110) {
printf("6");
}
if (temp == 111) {
printf("7");
}
if (temp == 1000) {
printf("8");
}
if (temp ==1001) {
printf("9");
}
if (temp == 1010) {
printf("A");
}
if (temp == 1011) {
printf("B");
}
if (temp == 1100) {
printf("C");
}
if (temp == 1101) {
printf("D");
}
if (temp == 1110) {
printf("E");
}
if (temp == 1111) {
printf("F");
}
if (binaryNum < 1) {
printf("\n");
break;
}
i++;
}
}
Can someone help me with that please? TY!
And if someone has a better way to do it I will be happy to see, because my way is very long.

You need just two functions, one of which is a recursive function:
int f_putchar(char c)
{
write(1, &c, 1);
return 1;
}
void f_hex(int nb)
{
char *hex = "0123456789abcdef";
if (nb < 16)
{
f_putchar(hex[nb]);
}
else
{
f_hex(nb / 16);
f_hex(nb % 16);
}
}

Related

Alarm clock in C

The code runs perfectly until it prints xx.00.00 which it prints twice. All the other code runs without a problem but each time goes from 23.59.59 -) 00.00.00 it gets printed twice. PLEASE HELP ME
#include <stdio.h>
void check(int number) {
if (number < 10) {
printf("0%d", number);
}
else {
printf("%d", number);
}
}
void count(int present_time, int time_for_alarm) {
int present_hour = present_time/10000;
int present_min = (present_time/100) % 100;
int present_sec = (present_time % 100);
int alarm_hour = time_for_alarm/10000;
int alarm_min = (time_for_alarm/100) % 100;
int alarm_sec = (time_for_alarm % 100);
while (present_hour != alarm_hour) {
if (present_hour == alarm_hour && present_min == alarm_min && present_sec == alarm_sec) {
printf("ALARM");
}
else {
if (present_sec <= 60) {
present_sec++;
if (present_sec == 60) {
present_sec = 0;
present_min++;
}
if (present_min == 60) {
present_min = 0;
present_hour++;
}
if (present_hour == 24) {
present_hour = 0;
}
check(present_hour);
printf(":");
check(present_min);
printf(":");
check(present_sec);
printf("\n");
}
}
}
while (present_min != alarm_min) {
if (present_hour == alarm_hour && present_min == alarm_min && present_sec == alarm_sec) {
printf("ALARM");
}
else {
if (present_sec <= 60) {
present_sec++;
if (present_sec == 60) {
present_sec = 0;
present_min++;
}
check(present_hour);
printf(":");
check(present_min);
printf(":");
check(present_sec);
printf("\n");
}
}
}
while (present_sec != alarm_sec) {
check(present_hour);
printf(":");
check(present_min);
printf(":");
check(present_sec);
printf("\n");
present_sec++;
}
}
int main() {
int present_time, time_for_alarm;
printf("What time is it? (HHMMSS)");
scanf("%d", &present_time);
printf("What time should the alarm go off? (HHMMSS)");
scanf("%d", &time_for_alarm);
count(present_time, time_for_alarm);
printf("ALARM");
return 0;
}
Issue is right here:
while (present_sec != alarm_sec) {
check(present_hour);
printf(":");
check(present_min);
printf(":");
check(present_sec);
printf("\n");
present_sec++;
}
In every other loop, you advance present_sec first, then print the time. In this loop, you advance after. When you reach the correct hour and minute, you enter this loop, and you will always duplicate the time here. Try inputting 225555 and 225605. You will see 22:56:00 duplicated.

Stack Paren Checker Not Working in C Code

I am attempting to build a parenthesis checker in C using a homebuilt stack, but the stack is an array that prevents my program from working by returning an array of random numbers. Please assist.
#define STACK_SIZE 100
#include <stdio.h>
char stack[STACK_SIZE];
int sp=0;
/*
* Pushes character c onto the stack.
* Returns 0 if successful.
* Returns -1 if an error occurs. (Stack full).
*/
int push (char c)
{
if (sp >= STACK_SIZE) {
printf("c");
return -1;
}
else {
stack[sp] = c;
sp++;
return 0;
}
}
/*
* Pops next character off the stack.
* Returns the char if successful.
* Returns -1 if an error occurs. (Stack empty).
*/
int pop ()
{
if (sp == 0) {
return -1;
}
else {
sp--;
return stack[sp];
}
}
/*
* Returns the current size of the stack.
*/
int stackSize()
{
printf("%i", sp);
return sp;
}
void printStack()
{
//TODO
}
int main ()
{
int i;
for (i = 0; i < 100; i++) {
stack[i] = 0;
}
int null = 0;
char b;
char a = getchar();
while (a != EOF) {
if (a == '(') {
if (stackSize() >= 100) {
printf("Error. Stack Full!\n");
return -1;
}
push(')');
}
else if (a == '{') {
if (stackSize() >= 100) {
printf("Error. Stack Full!\n");
return 1;
}
push('}');
}
else if (a == '[') {
if (stackSize() >= 100) {
printf("Error. Stack Full!\n");
return 1;
}
push(']');
}
else if (a == ')') {
b = pop();
if (stackSize() == 0) {
printf("Found %c. No matching character\n", a);
return 2;
}
else if (a != b) {
printf("Found %c, expected ).\n", a);
return 2;
}
}
else if (a == '}') {
b = pop();
if (stackSize() == 0) {
printf("Found %c. No matching character\n", a);
return 2;
}
else if (a != b) {
printf("Found %c, expected }.\n", a);
return 2;
}
}
else if (a == ']') {
b = pop();
if (stackSize() == 0) {
printf("Found %c. No matching character\n", a);
return 2;
}
else if (a != b) {
printf("Found %c, expected ].\n", a);
return 2;
}
}
}
if (stackSize() != 0) {
printf("Expecting %c, found end of input.\n", a);
return 3;
}
printf("Well formatted input.\n");
return 4;
}
Once I use a file as input, the program spits out roughly 100 random numbers and the "Error. Stack Full!" message. I can not get around this. Any help is welcomed and would be greatly appreciated. Thank you!

Roman Numeral To Decimal

Trying to implement a very simple Roman Numeral to Decimal converter but can't seem to figure out a way for the program to return -1 if any non-roman numeral characters are in the string. This is what I have so far.
#include <stdio.h>
#include <ctype.h>
int convertFromRoman(const char *s)
{
int i = 0;
int total = 0;
while (s[i] != '\0') {
if (isalpha(s[i]) == 0) {
return -1;
}
if (toupper(s[i]) == 'I') {
total += 1;
}
if (toupper(s[i]) == 'V') {
total += 5;
}
if (toupper(s[i]) == 'X') {
total += 10;
}
if (toupper(s[i]) == 'L') {
total += 50;
}
if (toupper(s[i]) == 'C') {
total += 100;
}
if (toupper(s[i]) == 'D') {
total += 500;
}
if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}
i++;
}
if (total == 0) {
return -1;
}
return total;
}
int main()
{
printf("%d\n", convertFromRoman("XVII"));
printf("%d\n", convertFromRoman("ABC"));
}
The first one should return 17 and the second one should return -1. However they both return -1 but if I remove the else statement, the first one returns 17 and the second one returns 100.
Any help is appreciated.
Change if() if() if() else to if() else if () else if() else
if (toupper(s[i]) == 'I') {
total += 1;
}
else if (toupper(s[i]) == 'V') {
total += 5;
}
else if (toupper(s[i]) == 'X') {
total += 10;
}
....
else if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}
Not really an answer, just a bit of fun/alternate way of looking at the problem. It does solve the problem if you're not considering ordering just adding "digit" values.
char *romanNumerals = "IVXLCDM";
int values[] = { 1, 5, 10, 50, 100, 500, 1000 };
int convertFromRoman(const char *s) {
int val = 0;
for (int i = 0; s[i]; i++) {
char *idx;
if (NULL == (idx = strchr(romanNumerals, toupper(s[i])))) {
return -1;
}
val += values[idx - romanNumerals];
}
return val;
}

Changing function to accept integer instead of char pointer to convert binary to octal and hex in C

Currently I have code for converting a char pointer that holds binary characters and converts them to hex and octal representations.
The way my code has progressed, I now have an integer binary number, it is no longer a char pointer, but I still want to convert it to either hex and octal.
So, the code I have converts: "1101" into a hex or octal equivalent, but I current have 1101 as an integer value, but still want to convert that to hex or octal.
I do not know how to rewrite the code to accept an integer binary as an argument instead of a char * binary. Or how to change the int I have into a char pointer so that it can successfully go through the conversion function.
Here's the code for the function call that current works with a char pointer to a binary representation of a number, converting it into an octal or hex representation:
output = binaryBaseChange(output, 3); //for binary to octal conversion
output = binaryBaseChange(output, 4); //for binary to hex conversion
Here's the conversion function using the char * bin argument:
char * binaryBaseChange (char * bin, int size_of_digit) {
int offset = 0;
int i = 0;
int j = 4;
int k = 0;
int number_of_hex_digits = 0;
char* substr;
char * out;
int r = 0;
while(((strlen(bin) + offset) % size_of_digit) != 0) {
offset++;
}
out = malloc((strlen(bin) + offset) / size_of_digit+1);
out[(strlen(bin)+offset)/size_of_digit] = '\0';
r = (int)strlen(bin) + offset;
bin = pad_bin(bin, r);
number_of_hex_digits = (int)strlen(bin)/size_of_digit;
while (k < number_of_hex_digits) {
substr = strndup(bin+i, j);
substr[size_of_digit] = '\0';
i = i + size_of_digit;
j = j + size_of_digit;
if (size_of_digit == 4) {
out[k] = single_digit_bin_to_hex(substr);
} else if (size_of_digit == 3) {
out[k] = single_digit_bin_to_oct(substr);
}
free(substr);
k++;
}
free(bin);
out[k] = '\0';
return out;
}
Here are the functions called within the conversion function:
char single_digit_bin_to_oct (char * bin_dig) {
if (strcmp(bin_dig, "000") == 0) {
return '0';
} else if (strcmp(bin_dig, "001") == 0) {
return '1';
} else if (strcmp(bin_dig, "010") == 0) {
return '2';
} else if (strcmp(bin_dig, "011") == 0) {
return '3';
} else if (strcmp(bin_dig, "100") == 0) {
return '4';
} else if (strcmp(bin_dig, "101") == 0) {
return '5';
} else if (strcmp(bin_dig, "110") == 0) {
return '6';
} else {
return '7';
}
}
char single_digit_bin_to_hex (char *bin_dig) {
if (strcmp(bin_dig, "0000") == 0) {
return '0';
} else if (strcmp(bin_dig, "0001") == 0) {
return '1';
} else if (strcmp(bin_dig, "0010") == 0) {
return '2';
} else if (strcmp(bin_dig, "0011") == 0) {
return '3';
} else if (strcmp(bin_dig, "0100") == 0) {
return '4';
} else if (strcmp(bin_dig, "0101") == 0) {
return '5';
} else if (strcmp(bin_dig, "0110") == 0) {
return '6';
} else if (strcmp(bin_dig, "0111") == 0) {
return '7';
} else if (strcmp(bin_dig, "1000") == 0) {
return '8';
} else if (strcmp(bin_dig, "1001") == 0) {
return '9';
} else if (strcmp(bin_dig, "1010") == 0) {
return 'A';
} else if (strcmp(bin_dig, "1011") == 0) {
return 'B';
} else if (strcmp(bin_dig, "1100") == 0) {
return 'C';
} else if (strcmp(bin_dig, "1101") == 0) {
return 'D';
} else if (strcmp(bin_dig, "1110") == 0) {
return 'E';
} else if (strcmp(bin_dig, "1111") == 0){
return 'F';
} else {
fprintf(stderr, "ERROR");
return 'X';
}
}
char * pad_bin (char * bin, int n) {
int bin_len = (int)strlen(bin);
int dif = n - bin_len;
char * new_bin = malloc(n + 1);
int i = 0;
int j = 0;
memset(new_bin,0,n+1);
if (n == 0) {
return bin;
} else for (;i <= n; i++) {
if (i < dif) {
new_bin[i] = '0';
} else {
new_bin[i] = bin[j];
j++;
}
}
return new_bin;
}

scanf function with list of numbers

The program is supposed to read in digits one after the other to see if they are consecutive numbers or not. The second digit seems to be scanning as 21 all the time for some reason. Could anyone show me where i am going wrong? Thanks.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a=1, e=1,n, digit1, compared;
char y, z;
scanf("n=%d, digits=%c%c", &n, &y, &z);
digit1 = atoi(&y);
compared = atoi(&z);
if(digit1 == 0)
{
printf("False");
}
else if(compared == (digit1 + 1))
{
digit1++;
for(a = 1;a < (n - 1);a++)
{
scanf("%c", &z);
compared = atoi(&z);
if(compared == digit1 + 1)
{
e++;
digit1++;
}
}
if(e == (n - 1))
{
printf("True\n");
}
else
{
printf("False");
}
}
else if(compared == (digit1 - 1))
{
digit1--;
for(a = 1;a < (n - 1);a++)
{
scanf("%c", &z);
compared = atoi(&z);
if(compared == (digit1 - 1))
{
e++;
digit1--;
}
}
if(e == (n - 1))
{
printf("True\n");
}
else
{
printf("False");
}
}
return 0;
}

Resources