How To Convert Int Type To Char Type


13.04.2011

How To Convert Int Type To Char Type

Programming language can save data by using different kind of data. A common used data type for saving numbers is the int, which uses a 4-byte or 8-byte memory section. Another very used data type is called a char, and it can store values in a 1-byte memory segment.

Converting an int to a char may cause many problems because there is no space to save all of the bytes from the ant into the char. But the great news is that you can use more chars to save only one int:

  1. Enter your IDE and start up a new project. In the main workspace are you will see a new blank source code file.

  2. Define the int type you want to convert over to a char and set a value: ex. unsigned int numberToConvert = 456734645.

  3. Print the value of the number in hexadecimal because you will need it to check your conversion later.

  4. Type ‘unsigned int numberOfChars = sizeof(int)/sizeof(char);’ so you find out how many chars can fit¬†inside an int type on your PC.

  5. Define the chars that will hold the int: unsigned char destination[numberOfChars];.

  6. The next step is to create a for loop structure. The ‘design’ of the for loop:¬†for(int i = 0; i < numberOfChars; i++)

  7. The first eight bits have to be assigned to the first char in the array but keep in mind that it will work only if your computer is based on 8-bytes system: estination[i] = numberToConvert >> (8 * i);

  8. Print the values of each char in hexadecimal:¬†printf(“%xn”, destination[i] );

  9. Now the only thing you have to do is compile and run the program.

Tags: char, type, data, save, chars, only, byte, bytes, many, values, because, define, print, numbertoconvert, value, memory, numberofchars, first, used, convert, fit‚†inside, sizeofintsizeofchar, find, hold, destinationnumberofchars, int‚†unsigned, destinationi, later, compile, hexadecimal