Data Types: Storing character in integer and vice versa with Program
This blog explains about Data Types: Storing character in integer and vice versa with Program and is given below :
_______________________________________________________________________________
Hi Friends,
Today, we are going to see about how to
Data Types: Storing character in integer and vice versa with Program
store character in ‘int’ variable and number in ‘char’ datatype.
Storage of integer and character values in C
Integer and character variables are used so often in the programs, but how these values are actually stored in C are known to few.
Below are a few examples to understand this:
- Taking a positive integer value as char:
#include <stdio.h>
int
main()
{
char
a = 278;
printf
(
"%d"
, a);
return
0;
}
Output:
22
Explanation:
- First, compiler converts 278 from decimal number system to binary number system(100010110) internally and then takes into consideration only the first 8 bits from the right of that number represented in binary and stores this value in the variable a. It will also give warning for overflow.
- Taking a negative integer value as char:
#include <stdio.h>
int
main()
{
char
a = -129;
printf
(
"%d"
, a);
return
0;
}
Output:
127
Explanation:
- First of all, it should be understood that negative numbers are stored in the 2’s complement form of their positive counterpart. The compiler converts 129 from decimal number system to binary number system(10000001) internally, and then, all the zeroes would be changed to one and one to zeroes(i.e. do one’s complement)(01111110) and one would be added to the one’s complement through binary addition to give the two’s complement of that number (01111111). Now, the rightmost 8 bits of the two’s complement would be taken and stored as it is in the variable a. It will also give warning for overflow.
Let us see it through a sample program below.
public class IntAndChar {
public static void main(String[] args) {
int a=’A’;
char b=70;
System.out.println(a);
System.out.println(b);
}
}
Output:
65
F
this output can be possible because,
ASCII Character
——————————-
65 A
66 B
67 C
int a =’A’;
‘A’ convert into its 65(ASCII) and store into integer variable a.
char b=70;
70(ASCII) convert into character ‘F’ and store into char variable b.
_______________________________________________________________________________
REFERENCES :
https://www.geeksforgeeks.org/storage-of-integer-and-character-values-in-c/