Code Snippets
        C/C++ Code Snippets
        C program to print ASCII values of a string.
        By: IncludeHelp, On  17 OCT 2016
        
        
  
    Advertisement
    
    
    
  
  
    Advertisement
    
    
  
 
 
        
        
        In this program we will learn how to print ASCII value of all characters of a string in c programming language?
        In this example we will read a string and print ASCII values of all characters in hexadecimal code. To print ASCII values in very simple, we have to just access one by one character from the string (by running a loop from 0 to NULL character) and prints the value using %02X format specifier. 
        %02X prints the 2 bytes 0 padded Hexadecimal value of any character.
                        
               
        C program (Code Snippet) - Print ASCII of a String
        Let’s consider the following example:
/*c program to print ascii values of a string*/
#include <stdio.h>
int main(){
	char str[100];
	int i;
	
	printf("Enter a string: ");
	fgets(str,100,stdin); 
	//scanf("%s",str);
	
	printf("String is: %s\n",str);
	printf("ASCII value in Hexadecimal is: ");
	for(i=0; str[i]!='\0'; i++){
		printf("%02X ",str[i]);
	}
	printf("\n");
	
	return 0;
}
    
Output
    Enter a string: Hello World!
    String is: Hello World! 
    ASCII value in Hexadecimal is: 48 65 6C 6C 6F 20 57 6F 72 6C 64 21 0A