How get ASCII of a string - c

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;
}

Related

Assignment makes pointer from integer without a cast and vice versa in c

I'm trying to write a program that gets a string, and a number, and calculates the length of it and shifting all the elents right.
I have 2 errors:
1.assignment makes pointer from integer without a cast.
2.assignment makes integer from pointer without a cast.
#include <stdio.h>
#include <string.h>
#define N 10
int myStrlen(char*);
void shiftRight(char*, int);
int main() {
char str[N] = {0};
int num = 0;
int len;
/* input of the string */
scanf("%s",str);
scanf("%d",&num);
len=myStrlen(str);
if(num>=0) {
shiftRight(str, num);
printf("%s\n",str);
}
else
{
printf("%s\n", str);
}
return 0;
}
int myStrlen(char*str)
{
int my_len=0;
while (str[my_len] != '\0')
{
my_len++;
}
return my_len;
}
void shiftRight(char* str, int num)
{
int i;
char* j;
int count;
j=(str[N-1]);
for(count=0;count<num;count++)
{
for(i=N-1;i>0;--i)
{
str[i]=str[i-1];
}
str[0]=j;
}
}
Your answers are welcome,anf if you anything wrong with this code,please mention it.
As your compiler will have told you, pointer from integer without a cast is at
j=(str[N-1]);
And integer from pointer is at
str[0]=j;
You should have declared j as char j;
But now when i run it, and typing lets say ball as a string and 1 to
be a number, i get nothing from the program instead of getting "lbal"
You have all the correct elements but that's not enough. Writing a program is telling a story, you need to set the scene, describe what happens along the way and conclude your narrative. A story with elements out of order is nonsense, as is a program.
Specific issues with your code: you're saving of the last character (to restore it to the beginning of the string) is in the wrong place; you're using the allocation of the string when you should be using it's length (and conveniently, you have a function for that!); this is really more of a rotation than a shift; use the most descriptive variable names you can, not the shortest you can get away with; pick one indentation style and stick with it -- it can change between programs you write but shouldn't change within an individual program.
Below is a rework of your code addressing some of the issues above:
#include <stdio.h>
#define STRING_SIZE 10
int myStrlen(char *string)
{
int length = 0;
while (string[length] != '\0')
{
length++;
}
return length;
}
void rotateRight(char *string, int number)
{
int length = myStrlen(string);
for (int count = 0; count < number; count++)
{
char j = string[length - 1];
for (int i = length - 1; i > 0; i--)
{
string[i] = string[i - 1];
}
string[0] = j;
}
}
int main()
{
char string[STRING_SIZE] = {0};
int number = 0;
/* input of the string */
scanf("%s", string);
scanf("%d", &number);
if (number > 0)
{
rotateRight(string, number);
printf("%s\n", string);
}
else
{
printf("%s\n", string);
}
return 0;
}
OUTPUT
% ./a.out
elephant
3
anteleph
%

Problems with simple c task

So after a few years of inactivity after studying at uni, I'm trying to build up my c experience with a simple string reverser.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
reverser();
return(0);
}
int reverser(){
printf("Please enter a String: ");
//return (0);
int len;
char input[10];
scanf("%s",&input);
int quit = strcmp(input,"quit");
if(quit == 0){
printf("%s\n","Program quitting");
return(0);
}
len = strlen(input);
printf("%i\n",len);
char reversed[len];
int count = 0;
while (count <= (len-1)){
//printf("%i\n",(len-count));
reversed[count] = input[(len-1)-count];
count++;
}
//printf("%s\n",input);
printf(reversed);
printf("\n");
reverser();
}
When I input "hello", you would expect "olleh" as the response, but I get "olleh:$a ca&#",
How do I just get the string input reversed and returned?
Bombalur
Add a '\0' at the end of the array. (as in, copy only chars until you reach '\0' - which is the point at array[strlen(array)], then when you're done, add a '\0' at the next character)
Strings are conventionally terminated by a zero byte. So it should be
char reversed[len+1];
And you should clear the last byte
reversed[len] = (char)0;
you forgot the \0 at the end of the string
This is because you are creating an array with size 10. When you take in some data into it (using scanf) and the array is not filled up completely, the printf from this array will give junk values in the memory. You should iterate for the length of the input by checking \n.
must have a size + 1 to string length so that you can have a \0 at the end of string that will solve your problem
The following is a (simple and minimal implementation of) string reverse program (obviously, error conditions, corner cases, blank spaces, wider character sets, etc has not been considered).
#include <stdio.h>
int strlen(char *s)
{
char *p = s;
while (*p)
p++;
return p - s;
}
char * strrev(char a[])
{
int i, j;
char temp;
for (i=0, j=strlen(a)-1 ; i<j ; i++, j--) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
int main()
{
char str[100];
printf("Enter string: ");
scanf("%s", str);
printf("The reverse is %s \n", strrev(str));
return 0;
}
Hope this helps!

Reverse a string containing ASCII chars and non-ASCII chars

I got a problem about how to reverse a string containing this 'abcd汉字efg'.
str_to_reverse = "abcd汉字efg"; /* those non-ASCII chars are Chinese characters, each of them takes 2 bytes */
after reversion, it should be:
str_toreverse = "gfe字汉dcba";
I thought, to reverse the string, I gotta identify those non-ASCII chars, because I think that simply reversing every byte won't get the right answer.
How can I do it?
PS:
I wrote this program under Ubuntu, 32-bit.
then I printed every byte:
for(i = 0; i < strlen(s); i++)
printf("%c", s[i]);
I got some gibberish text instead of "汉字".
Pure C89 answer:
#include <stdlib.h>
#include <stdio.h>
#include <locale.h>
#include <string.h>
int main()
{
char const* str;
size_t slen;
char* rev;
setlocale(LC_ALL, "");
str = "abcd汉字efg";
printf("%s\n", str);
slen = strlen(str);
rev = malloc(slen+1)+slen;
*--rev = '\0';
while (*str != '\0') {
int clen, i;
clen = mblen(str, slen);
if (clen == -1) {
fprintf(stderr, "Bad encoding\n");
return EXIT_FAILURE;
}
for (i = 0; i < clen; ++i) {
*--rev = str[clen-1-i];
}
str += clen;
}
printf("%s\n", rev);
return 0;
}
If the string is encoded as utf8, it is pretty simple. You can obtain the length of well formed utf8 sequences by inspecting only the first byte.
In a first pass you reverse only the utf8 "subsequences" (those with length > 1)
In a second pass you reverse the whole string.
Voila.

Convert char array to int array?

I'm beginner in C.
I have an char array in this format for example "12 23 45 9".
How to convert it in int array {12,23,45,9}?
Thanks in advance.
Use sscanf, or strtol in a loop.
The traditional but deprecated way to do this would be to use strtok(). The modern replacement is strsep(). Here's an example straight off the man page for strsep():
char **ap, *argv[10], *inputstring;
for (ap = argv; (*ap = strsep(&inputstring, " \t")) != NULL;)
if (**ap != '\0')
if (++ap >= &argv[10])
break;
That breaks inputstring up into pieces using the provided delimiters (space, tab) and iterates over the pieces. You should be able to modify the above to convert each piece into an int using atoi(). The main problem with strsep() is that it modifies the input string and is therefore not thread safe.
If you know that the input string will always contain the same number of ints, another approach would be to use sscanf() to read all the ints in one go:
char *input = "12 23 45 9";
int output[5];
sscanf(inputstring, "%d %d %d %d %d", &output[0], &output[1], &output[2], &output[3], &output[4]);
You can calculate the individual digits by using the following technique (but it won't convert them into the whole number):
Note I am using an int iteration loop to make it readable. Normally you'd just increment the char pointer itself:
void PrintInts(const char Arr[])
{
int Iter = 0;
while(Arr[Iter])
{
if( (Arr[Iter] >= '0') && (Arr[Iter]) <= '9')
{
printf("Arr[%d] is: %d",Iter, (Arr[Iter]-'0') );
}
}
return;
}
The above will convert the ASCII number back into an int number by deducting the lowest ASCII representation of the 0-9 set. So if, for example, '0' was represented by 40 (it's not), and '1' was represented by 41 (it's not), 41-40 = 1.
To get the results you want, you want to use strtok and atoi:
//Assumes Numbers has enough space allocated for this
int PrintInts(const int Numbers[] const char Arr[])
{
char *C_Ptr = strtok(Arr," ");
int Iter = 0;
while(C_Ptr != NULL)
{
Numbers[Iter] = atoi(C_Ptr);
Iter++;
C_Ptr = strtok(NULL," ");
}
return (Iter-1); //Returns how many numbers were input
}
You will need stdlib.h
//get n,maxDigits
char** p = malloc(sizeof(char*) * n);
int i;
for(i=0;i<n;i++)
p[i] = malloc(sizeof(char) * maxDigits);
//copy your {12,23,45,9} into the string array p, or do your own manipulation to compute string array p.
int* a = malloc(sizeof(int) * n);
int i;
for(i=0;i<n;i++)
a[i] = atoi(p[i]);
What about:
const char *string = "12 23 45 9";
int i, numbers[MAX_NUMBERS]; //or allocated dynamically
char *end, *str = string;
for(i=0; *str && i<MAX_NUMBERS; ++i)
{
numbers[i] = strtol(str, &end, 10);
str = end;
};
Though it maybe that you get a trailing 0 in your numbers array if the string has whitespace after the last number.

convert array of characters to array of integers in C

I'm passing in an argument to a C program:
program_name 1234
int main (int argc, char *argv[]) {
int length_of_input = 0;
char* input = argv[1];
while(input[length_of_input]) {
//convert input from array of char to int
length_of_input++;
}
}
I want to be able to use each digit of the argument passed into the function separately as an integer. atoi(input[]) throws a compile-time error.
This code doesn't compile:
while(input[length_of_input]) {
int temp = atoi(input[length_of_input]);
printf("char %i: %i\n", length_of_input, temp);
length_of_input++;
}
int i;
for (i = 0; input[i] != 0; i++){
output[i] = input[i] - '0';
}
Seeing as this is homework you could also do
output[i] = input[i] - '0';
but be careful that input[i] is actually a digit (i.e. it's between '0' and '9')!
First you have to check how much space you need to allocate for the integer array. This can be done with strlen() function or iterating trough the string and checking how many valid characters are found. Then you must iterate through the string and convert every (valid) character to equivalent integer number. It is hard to use atoi() or scanf() family of functions here since they except array as input. Better solution would be to write your own little converter function or snippet for the conversion.
Here is small example app which converts string to array of ints. If the character is not a valid decimal digit, -1 is placed into array.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int length, i;
int *array;
char *input = argv[1];
/* check if there is input */
if(input == NULL) return EXIT_FAILURE;
/* check the length of the input */
length = strlen(input);
if(length < 1) return EXIT_FAILURE;
/* allocate space for the int array */
array = malloc(length * sizeof *array);
if(array == NULL) return EXIT_FAILURE;
/* convert string to integer array */
for(i = 0; i < length; ++i) {
if(input[i] >= '0' && input[i] <= '9')
array[i] = input[i] - '0';
else
array[i] = -1; /* not a number */
}
/* print results */
for(i = 0; i < length; ++i)
printf("%d\n", array[i]);
/* free the allocated memory */
free(array);
return EXIT_SUCCESS;
}
Also check these questions:
Convert a character digit to the corresponding integer in C
How to convert a single char into an int
How to convert char to integer in C?
C Convert String to Ints Issue
You can to test if argument is a number whith isdigit()
http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
and use atoi function .
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
And be careful in use
char* input = argv[1];
copy the string from argv to input (after to use malloc), it's better.

Resources