How to read hexadecimal numbers from input in C? [duplicate] - c

This question already has an answer here:
scanf a big hexadecimal value
(1 answer)
Closed 2 years ago.
I want to read a hexadecimal number from the user. I use C99.
My idea was to read a char and check by the character code what hexadecimal number it could be.
Here is the code:
#include <stdio.h>
int main() {
char count;
int c;
printf("Enter hex value:\n");
scanf("%c", &count);
if (count >= 48 && count <= 57) {
c = count - 48;
}
if (count >= 65 && count <= 70) {
c = count - 55;
}
if (count >= 97 && count <= 102) {
c = count - 87;
}
printf("%d", c);
return 0;
}
But I think there should be easier ways. Because it can only read one number and not longer ones.
Is there anything that could help?

You can use scanf with %x:
#include <stdio.h>
int main() {
int a;
scanf("%x", &a);
printf("%d", a);
}
Output:
a -> 10
ff -> 255

Related

C code showing ASCII instead of character

I've only used C++ in the past and I was trying to convert my decimal to hex code to C. When trying to do so, I'm noticing when I try to print out a character, it prints out the ASCII value instead. I'm unsure of why it is doing this. Example: 10 in hex = A, however it prints out 65 instead. Any help would be appreciated.
#include<stdio.h>
#include<stdlib.h>
int main ()
{
int num = 0;
printf("Please enter an integer ");
scanf("%d",&num);
//shown as 8 in the example
char hex[8];
char hex_values[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int count = 0;
while(num > 0)
{
int spot = num % 16;
hex[count] = hex_values[spot];
num = num / 16;
count++;
printf("%d ", hex[count-1]);
}
//places zeros in front of the array... in an easy way
int zeros = 8 - count;
for(int q = 0; q < zeros; q++)
{
printf("%c", '0');
}
}
You have to print with '%c' to get the ASCII representation of a number because in C char are just unsigned short int
printf("%c ", hex[count-1]);

Palindrome C program convert capital letters to small letters [duplicate]

This question already has answers here:
Implementation of ToLower function in C
(4 answers)
Closed 5 years ago.
At school Im working on a palindrome C program. I'm almost done, but I would like my program to mark both 'Anna' and 'anna' as a palindrome. I tried some stuff out but nothing really worked.
My code :
#include <stdio.h>
#include <string.h>
int main() {
char palindroom[50],a;
int lengte, i;
int woord = 0;
printf("This program checks if your word is a palindrome.\n");
printf("Enter your word:\t");
scanf("%s", palindroom);
lengte = strlen(palindroom);
for (i = 0; i < lengte; i++) {
if (palindroom[i] != palindroom[lengte - i - 1]) {
woord = 1;
break;
}
}
if (woord) {
printf("Unfortunately, %s is not palindrome\n\n", palindroom);
}
else {
printf("%s is a palindrome!\n\n", palindroom);
}
getchar();
return 0;
}
I've seen some people using tolower from ctype.h but I'd like to avoid that.
So my question is : how do I convert all uppers to lowers in a string?
[ps. some words I may code might seem odd, but that's Dutch. Just erase an o and you'll understand]
Thanks.
the difference between uppercase and lowercase in ASCII table is 32 so you can add 32 if an uppercase letter is in the input to convert it to lowercase ( http://www.asciitable.com/ ) :
if ((currentletter > 64) && (currentletter < 91))
{
char newletter;
newletter = currentletter + 32;
str[i] = newletter;
}
else
{
str[i] = currentletter;
}
modified program :
#include <stdio.h>
#include <string.h>
int main() {
char palindroom[50],a;
int lengte, i;
int woord = 0;
printf("This program checks if your word is a palindrome.\n");
printf("Enter your word:\t");
scanf("%s", palindroom);
lengte = strlen(palindroom);
for (i = 0; i < lengte; i++)
{
if (palindroom[i] > 64 && palindroom[i] < 91)
{
palindroom[i] = palindroom[i] + 32;
}
if (palindroom[i] != palindroom[lengte - i - 1]) {
woord = 1;
break;
}
}
if (woord) {
printf("Unfortunately, %s is not palindrome\n\n", palindroom);
}
else {
printf("%s is a palindrome!\n\n", palindroom);
}
getchar();
return 0;
}
65 is the decimal representation of A in the ASCII table, 90 is the decimal representation of Z while a is 97 ( = 65 +32 ) and z is 122 ( = 90 +32 )
If you want don't want to use tolower or toupper you can do this:
// tolower
char c = 'U';
char lower_u = c | 0x20
// toupper
char c = 'u';
char upper_u = c & 0xdf
In ASCII the difference between a lower and an upper character is the 5th bit.
When The 5th bit is 0, you get an upper character, when the 5th bit is 1, you get a lower character.

C program to find total number of digits [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wrote this program to find the total number of digits from a line of text entered by user. I am having error on using getchar(). I can't seem to figure out what am I doing wrong?
#include <stdio.h>
#define MAX_SIZE 100
void main() {
char c[MAX_SIZE];
int digit, sum, i;
digit, i = 0;
printf("Enter a line of characters>");
c = getchar();
while (c[i] != '\n') {
digit = 0;
if (c [i] >= '0' && c[i] <= '9') {
digit++;
}
}
printf("%d\n", digit);
}
I will be adding all the digits I found using sum variable. but I am getting error on getchar() line. HELP??
You can enter a "line of text" without using an array.
#include <stdio.h>
#include <ctype.h>
int main(void) { // notice this signature
int c, digits = 0, sum = 0;
while((c = getchar()) != '\n' && c != EOF) {
if(isdigit(c)) {
digits++;
sum += c - '0';
}
}
printf("%d digits with sum %d\n", digits, sum);
return 0;
}
Note that c is of type int. Most of the library's character functions do not use char type.
Edit: added the sum of the digits.
Weather Vane's answer is the best and simplest answer. However, for future reference, if you want to iterate (loop through) an array, it would be easier to use a for loop. Also, your main function should return an int and should look like this: int main(). You will need to put a return 0; at the end of your main function. Here is a modified version of your program that uses a for loop to loop through the character array. I used the gets function to read a line of characters from the console. It does wait for the user to enter the string.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
char c[MAX_SIZE];
int digit = 0;
printf("Enter a line of characters>");
gets(c);
for (int i = 0; i < MAX_SIZE; i++)
{
if (c[i] == '\n') break; // this line checks to see if we have reached the end of the line. If so, exit the for loop (thats what the "break" statment does.)
//if (isdigit(c[i])) // uncomment this line and comment or delete the one below to use a much easier method to check if a character is a digit.
if (c [i]>= '0' && c[i] <= '9')
{
digit++;
}
}
printf("%d\n", digit);
return 0;
}
An easy of getting the number of digits in an integer is the use of log10() function which is defined in math.h header. Consider this program
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, const char *argv[]) {
system("clear");
unsigned int i, sum = 0, numberOfDigits;
puts("Enter a number");
scanf("%u", &i);
numberOfDigits = (int) (log10(x) + 1);
system("clear");
while(i != 0) {
sum += (i % 10);
i /= 10;
}
fprintf(stdout, "The sum is %i\n", sum);
fflush(stdin);
return 0;
}

Retrieving an int's binary value, outputting the ASCII the binary corresponds to

Not really sure how to word this.
I have the int 'value' = 121, which is 1111001 in binary.
1111001 from binary to ASCII = "y"
I was wondering how I can convert the int value 121 to be printed as an ASCII character. Is there a built in function in C to do this?
Code I wrote earlier for someone else's question and adapted to your question:
#include <stdio.h>
int main(void)
{
int nr_to_binary = 0;
printf("Number: ");
scanf("%d", &nr_to_binary);
int i = (sizeof(nr_to_binary) * 8);
for(; i > 0 ; i--)
{
printf("%d", (nr_to_binary >> (i - 1)) & 1);
}
printf("\n\nASCII value of %d is %c", nr_to_binary, nr_to_binary);
return 0;
}
Result
Number: 121
00000000000000000000000001111001
ASCII value of 121 is y

Print every number with 0 in their digits (Only natural) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
The program requires a user to insert a number. Let's say we put 149. Now the program prints every number that has 0 digits in them till the number 149 (Including the number). So it's going to be 10,20,30,40,50,60,70,80,90,100,101...110..140 [Let's say the limit would be till 10000]
I have been trying to do this, but i only added +10 to every one, but that cannot be done >100 where it is 101,102..
Use the function sprintf to convert an integer to a string and then search for the character '0' in the string. If found, then print the number. Here's a simple working program implementing this idea.
#include <stdio.h>
#include <string.h>
#define MAXLEN 50 // max number of digits in the input number
int main(void) {
char buf[MAXLEN + 1]; // +1 for the null byte appended by sprintf
char ch = '0'; // char to be searched for in buf
int i, x;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
sprintf(buf, "%d", i); // write i to the string buffer and append '\0'
if(strchr(buf, ch)) // strchr returns a pointer to ch if found else NULL
printf("%d\n", i);
}
return 0;
}
You can also extract each digit of an integer in the given range and check it for zero. Here's a naive implementation.
#include <stdio.h>
int main(void) {
int i, x;
int r;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
for(r = i; r > 0; r /= 10) {
if(r%10 == 0) {
printf("%d\n", i);
break;
}
}
}
return 0;
}
The simple approach would be to iterate through all natural numbers up to the target number and testing each of them to see if they have any zero digits. Note that the last digit of a non-negative integer i can be obtained as the remainder from division by the base (i % 10 here). Also remember that integer division in C truncates decimals, e.g., (12 / 10) == 1
As a start, consider to convert each number to char [] and then check whether it contains a '0' or not.
To read on:
How to check if a int var contains a specific number
Count the number of Ks between 0 and N
I think this would be the answer.
int j;
for(int i=1;i<150;i++){
j=i;
while(j>0)
{
if(j%10==0)
{
printf("%d\n",i);
break;
}
else
j=j/10;
}
}

Resources