How i take hex input into array from users c - c

I will take hex input from user into buffer array, but i don't take it, scanf does not appropriate. Input data like this (0x 06 41 42 43 0f 52 53). Also then i want to transform string to integer type some part of array. I used atoi, what is best way for it?
#include <stdio.h>
int main(){
char buffer[1000];
char dest[3];
int x;
//scanf("%s",buffer);
x=atoi(strncpy(dest,buffer+1,4))
}

The following simple function converts a string with a hexadecimal number to an integer:
int atox(const char *s)
{
int x= 0;
while (*s) {
x= x*16+(*s>'9'?(toupper(*s)-'A'+10):*s-'0');
s++;
}
return x;
}
and call it like:
printf("%02x\n",atox("42"));
printf("%02x\n",atox("a1"));
printf("%02x\n",atox("A1"));
Note that the string must be exactly the string to convert, so no spaces or whatever.

Here is the code using strtol function considering numbers as Hex inside the string (For base value 8 they will be octal):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s="00 06 41 42 43 0f 52 53";
char *endpoint=s;
int base=16,count=1;
long int result=0;
do
{
result=strtol(endpoint,&endpoint,base);
printf("value %d %ld\n",count,result);
count++;
}while((endpoint - s) < (size_t)strlen(s) );
return 0;
}

Related

working with methods to take in strings in C

I'm new to C and am having a lot of issues with arrays that keeps coming up. I'm trying to write a method that takes in a string ("1234") and returns the odd digits, however it keeps printing 49 and I don't know why? Does it have something to do with how I'm assigning the arrays?
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int print_odd_digits(char number[100]) {
int size = sizeof(number[100]);
for (int i = 0; i < size; i++) {
if (number[i] % 2 == 1) {
printf("%d\n", number[i]);
}
}
return 0;
}
int main(void) {
print_odd_digits("1234");
}
sizeof(number[100]) is equivalent to sizeof(char), which is 1. What you want seems strlen(number).
Elements of number are not values of digits but character codes of digits. To convert number characters to values, you can subtract '0'. (character codes for 0 to 9 are defined to be continuous in C).
%d is for printing integer and 49 is ASCII code for the character 1. Use %c to print character corresponding to passed integer.
You may want newline only on end of the characters.
Try this:
#include <stdio.h>
#include <string.h> /* for using strlen() */
int print_odd_digits(char number[100]) {
int size = strlen(number);
for(int i = 0; i < size; i++){
if((number[i] - '0') % 2 == 1){
printf("%c",number[i]);
}
}
printf("\n");
return 0;
}
int main(void) {
print_odd_digits("1234");
}
You have a type error here. You are working with the ascii codes for the text characters for digits. You need to use the atoi(char* str)
function to convert the digits to a corresponding number and use math to determine a particular digit or loop over the characters and subtract -'0' the ascii code for the digit zero as digits are sequential.
#include <stdlib.h>
#include <stdio.h>
int main() {
char* digit_one_str = "1";
char digit_9 = '9';
printf("digit one ascii value: %d\n", digit_one_str[0]); // first char in string digit one
int number_one = atoi(digit_one_str);
printf("digit one parsed from sttring by atoi: %d\n", number_one);
printf("digit 9 as char converted with -'0' trick: %d", (int)(digit_9 - '0'));
}
Further it is better practice to take in a char* and a length than to work with fixed sized arrays or using strlen() where you don't actually have to. In C a string ends in a terminating '\0' character which might not even be present if the code calling your function is buggy or malicious.

How to print ASCII codes for letters?

How do I create a program where the input of a letter (a-z) is converted to ASCII and printed out. I am stuck at the point where it has to show all the ASCII numbers before it.
Let's say if the user inputs the character c, I want to print out 97,98,99 for character inputs a,b,c respectively.
I am somewhat a beginner. Pretty sure I have to use a loop.
Hi, as I am a beginner can you possibly check my way of doing it, unsure where I am doing wrong. Your code has a few things which I am unfamiliar with. I am aiming to restrict it to only A-Z. So here's the code :
#include <stdio.h>
int main()
{
char c,z;
printf("Enter An English upper case letter: ");
scanf("%c", &z);
for (c=65;c<91;c++)
{
if(c==z)
printf("%c",z);
}
return 0;
}
#include <stdio.h>
void get_ASCII_value(char c)
{
printf("The ASCII value of %c = %d", c, c);
}
int main(void)
{
char c;
printf("Enter a character: ");
scanf("%c", &c);
get_ASCII_value(c);
return 0;
}
To clarify, %d prints the ASCII value for that specific char
As for your specific case:
#include <stdio.h>
int main()
{
char c,z;
printf("Enter An English upper case letter: ");
scanf("%c", &z);
if (z < 65 || z > 90)
return 0;
for (c = 65; c <= z; c++)
printf("The ASCII value of %c = %d\n", c, c);
return 0;
}
#include <stdio.h>
#include <stdint.h>
#include <limits.h>
int main(void)
{
for(uint8_t c = 0; c < UCHAR_MAX; ++c)
{
uint8_t out[2] = {c};
printf("%d (%s)\n", c, isprint(c)? out : "*unprintable*");
}
return 0;
}
###Output
Success #stdin #stdout 0s 4288KB
0 (*unprintable*)
1 (*unprintable*)
2 (*unprintable*)
3 (*unprintable*)
4 (*unprintable*)
5 (*unprintable*)
[....]
29 (*unprintable*)
30 (*unprintable*)
31 (*unprintable*)
32 ( )
33 (!)
34 (")
35 (#)
36 ($)
37 (%)
38 (&)
39 (')
40 (()
41 ())
42 (*)
43 (+)
[...]
65 (A)
66 (B)
67 (C)
68 (D)
69 (E)
70 (F)
71 (G)

Check if the number is even or odd

My program gives me error(not exactly an error but it just prints error instead of even or odd) even if I put a number or letters. The code works if I remove the isdigit checker(3rd line). I do no know what am I doing wrong. Can someone please help me. Thanks in advance. Here is my code.
int main()
{
int n;
printf("Input an integer\n");
scanf("%d", &n);
if(!isdigit(n))
{
print("error");
return 0;
}
n%2 == 0 ? printf("Even\n") : printf("Odd\n");
return 0;
}
isdigit is not for this purpose.
If you want to check if the input is vaild, one method is to load with %s and use strtol.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void print(const char *s) {
puts(s);
}
int main()
{
char nstr[100] = {0};
int n;
char *e;
printf("Input an integer\n");
scanf("%99s", nstr);
n=(int)strtol(nstr, &e, 10);
if(nstr[0] == '\0' || *e != '\0')
{
print("error");
return 0;
}
n%2 == 0 ? printf("Even\n") : printf("Odd\n");
return 0;
}
man -a isdigit
isdigit()
checks for a digit (0 through 9).
Thus isdigit fails if ascii value of n is not anything but
Oct Dec Hex Char
--------------------------
060 48 30 0
061 49 31 1
062 50 32 2
063 51 33 3
064 52 34 4
065 53 35 5
066 54 36 6
067 55 37 7
070 56 38 8
071 57 39 9
man -a ascii
thus,
if(!isdigit(n))
{
print("error");
return 0;
}
is not an appropriate option. you should probably find some other option to validate n.
The isdigit function checks a character to see if it is in the '0' to '9' range. More specifically, it checks if the ASCII value of the character is between 48 (the code for '0') and 57 (the code for '9').
You're passing an int to this function, not a character, so it's not appropriate to use this function here. Just remove this check and it will work.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("Please enter your number\n");
scanf("%d",&n);
if( n%2==0)
printf("The number is even\n");
else
printf("The number is odd\n");
System("pause");
return 0;
}
Check this one.

How get ASCII of a string

i need to get the ascii (int and hex format) representation of a string char by char. For example if i have the string "hello", i would get for int ascii 104 101 108 108 111
and for hex 68 65 6C 6C 6F
How about:
char *str = "hello";
while (*str) {
printf("%c %u %x\n", *str, *str, *str);
str++;
}
In C, A string is just a number of chars in neighbouring memory locations. Two things to do: (1) loop over the string, character by character. (2) Output each char.
The solution for (1) depends on the string's representation (0-terminated or with explicit length?). For 0-terminated strings, use
char *c = "a string";
for (char *i = c; *i; ++i) {
// do something with *i
}
Given an explicit length, use
for (int i = 0; i < length; ++i) {
// do something with c[i]
}
The solution for (2) obviously depends on what you are trying to achieve. To simply output the values, follow cnicutar's answer and use printf. To get a (0-terminated) string containing the representation,
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* convert a 0-terminated string to a 0-terminated string of its ascii values,
* seperated by spaces. The user is responsible to free() the result.
*/
char *to_ascii(const char *inputstring) {
// allocate the maximum needed to store the ascii represention:
char *output = malloc(sizeof(char) * (strlen(inputstring) * 4 + 1));
char *output_end = output;
if (!output) // allocation failed! omg!
exit(EXIT_FAILURE);
*output_end = '\0';
for (; *inputstring; ++inputstring) {
output_end += sprintf(output_end, "%u ", *inputstring);
//assert(output_end == '\0');
}
return output;
}
If you need to output an explicit-length string, use strlen() or the difference (size_t)(output_end-output).
int main()
{
enum type {decimal, hexa};
char *str = "hello";
char *temp_str = NULL;
temp_str = str;
static enum type index = decimal;
while (*str) {
if(index == decimal)
printf("%u\t", *str);
else
printf("%x\t",*str);
str++;
}
printf("\n");
if(index != hexa)
{
index = hexa;
str = temp_str;
main();
}
}
hope this will work fine as what u want, and if u want to store it in a uint8_t array, have to just declare an variable for it.
I know this is 5 years old but my first real program converted strings to ASCII and it was done in a clean and simple way by assigning a variable to getchar() and then calling it in printf() as an integer, all while it's in a loop of course, otherwise getchar() only accepts single characters.
#include <stdio.h>
int main()
{
int i = 0;
while((i = getchar()) != EOF)
printf("%d ", i);
return 0;
}
and here's the original version using the for() loop instead because I wanted to see just how small I could make the program.
#include <stdio.h>
int main()
{
for(int i = 0; (i = getchar()) != EOF; printf("%d ", i);
}
/* Receives a string and returns an unsigned integer
equivalent to its ASCII values summed up */
unsigned int str2int(unsigned char *str){
int str_len = strlen(str);
unsigned int str_int = 0;
int counter = 0;
while(counter <= str_len){
str_int+= str[counter];
printf("Acumulator:%d\n", str_int);
counter++;
}
return str_int;
}

How would I print out the address like the Hexdump function in UNIX

There I have this assignment where I am suppose to emulate the hexdump function from unix. I got my program to dump files into hex but i am having trouble printing the offset and the printable characters.
Here is my code:
/*performs a hex and an octal dump of a file*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LINESIZE 512
void hexdump(FILE *fp);
void octaldump(FILE *fp);
int main(int argc, char * argv[])
{
FILE *fp;
if((fp = fopen(argv[1], "rb+")) == '\0')
{
perror("fopen");
return 0;
}
hexdump(fp);
return 0;
}
void hexdump(FILE *fp)
{
char temp [LINESIZE];
size_t i = 0;
size_t linecount = 1;
long int address = 0;
while(fscanf(fp," %[^\n] ", temp) == 1)
{
printf("%5d", address);
for(i = 0; i < strlen(temp); i++)
{
printf("%02x ", temp[i]);
if(linecount == 16)
{
printf("\n");
linecount = 0;
}
linecount++;
}
printf(" | ");
for(i = 0; i < strlen(temp); i++)
{
if(temp[i] < 32)
{
printf(".");
}
else
{
printf("%c", temp[i]);
}
}
printf("\n");
}
}
As i said above, my program is suppose to print the offset then the hex value of the file padded with 0's, then the printable characters of the file like so.
0000000 7f 2a 34 f3 21 00 00 00 00 00 00 00 00 00 00 00 | test file
I managed to print out the printable characters, but they appear after the hex part. So if one line of hexcode extends to the next line, it prints the printable characters on the nextline.
For example:
2a 3b 4d 3e 5f
12 43 23 43 | asfdg df
How do i get it to print whatever character appears after one line of the hex characters?
PS: For some reason my program doesn't pad 0's for some reason.
EDIT1: I got the offset part, i just keep adding 16 to my address variable and keep printing
Since this is homework, I'll just give you some pointers on how to approach your problem. I'll be as vague as I can so as to not interfere with your learning.
First of all, don't use fscanf if you're writing a hex dumper, use fread instead. The scanf family of functions are meant for text and hex dumpers are usually used with binary data.
If you use fread and read just enough bytes at a time to fill one line of output, then you can produce your desired output with two for loops (one for hex, one for characters) followed by a single newline.
As far as your zero padding problem goes, read the printf man page, your "%5d" format string needs a little bit more.

Resources