How to Make a Hex Buffer From a Char C

  • Share
  • Print this article

The C programming language has many functions for handling numbers and strings, but converting from one format to another is not always straightforward. It can be useful during program development to view the exact contents of a string, including invisible characters. Converting your character buffers to hexadecimal can do just that.

Instructions

    • 1

      Open a text editor.

    • 2

      Enter the following code into the editor to pull in the required library functions:

      #include <stdio.h>
      #include <malloc.h>
      #include <string.h>

    • 3

      Initialize the variables you're going to use:

      int main(void) {
      int i = 0;
      char* c = "Hello World!";
      char* hex = NULL;
      hex = malloc( sizeof( *c ) * 2 );

    • 4

      Add the following lines at the end of the file:

      for( i = 0; c[i] != '\0'; i++ ) {
      sprintf( &hex[ i * 2 ], "%X", c[ i ] );
      }
      printf( "0x%s\n", hex );
      free( hex );
      return 0;
      }

      The "sprintf" function converts the string into hex one character at a time, storing the result into the hex buffer. The result is then printed to your screen and the program cleans up and exits.

    • 5

      Save your source code.

    • 6

      Compile and run the program to verify that it has converted the characters to hexadecimal.

Related Searches

Comments

Related Ads

Featured
View Mobile Site