In this tutorial, we will learn the unsigned char and its use in C programming with sample code.
unsigned char in C with Examples
The char type in C has the size of 1 byte and it can be a signed char and an unsigned char both have the same memory of 1 byte and are used to store a single character. The char variable stores the ASCII value of the character it represents. For example, if the char variable is storing the character ‘Z’, then it is storing the ASCII value of ‘Z’ which is 90.
If the data type is signed, it can contain zero, positive, and negative. The range of values a signed data type can hold is split evenly between positive and negative, with zero representing the middle value.
If the data type is unsigned, it contains only negative values, including zero. This is because all bits in the variable are used to represent the value rather than a bit reserved for the sign.
In C programming, the unsigned char data type is a useful option when dealing with dynamic values. Unlike short data or integers, unsigned char uses all 8 bits of its memory and has no signed bits. This means that unsigned data ranges from 0 to 255, allowing larger values to be stored in memory. By using unsigned char, you can optimize your code and save memory space while continuing to complete required tasks.
Syntax for Declaration
The following is the syntax for using the unsigned char data type in C:
Example 1: Storing and Displaying an unsigned char Value
Consider the following example that is used to store and display the unsigned char type value in C.
int main() {
unsigned char myChar = 'Z';
printf("My character is: %c", myChar);
return 0;
}
Example 2: Storing Multiple unsigned char Values in an Array
You can also store multiple unsigned char values in an array and here is a sample code for that.
Bottom Line
The unsigned char data type in C can be used to store characters and numbers. It uses 8 bits of memory and has no signed bits, allowing larger values to be stored in memory. By using unsigned char, you can improve your code and save memory space while doing what you want.