Home » C programming language

‘unsigned char’ for memory optimization in c programming



Developers generally use int to store integer values, without thinking about data range, if the data range is less, we should use unsigned char.

unsigned char

A type of char data type, unsigned char can store values between 0 to 255, so we can use unsigned char instead of short or int.

Here is an example:

#include <stdio.h>
int main()
{
	unsigned char value=0;
	
	printf("Value is: %d\n",value);
	
	value=50;
	printf("Value is: %d\n",value);
	
	value=255;
	printf("Value is: %d\n",value);
	
	return 0;	
}

Output

Value is: 0 
Value is: 50
Value is: 255

Here we can see clearly that unsigned char is able to store values from 0 to 255.

What will happen, if the value is greater than 255?

int main()
{
	unsigned char value=300;
	printf("Value is: %d\n",value);
	return 0;
}

Output

value is: 44

Here the vale will be 44

Why?

unsigned char store only 8 bits data into the memory, when the value is greater than only first 8 bits will be stored, see the given image.

unsigned char in c language

In this image 8 bits value is: 0010 1100 which is equivalent to 44.

If the data value if negative?

We can use char instead of unsigned char to store data value between -128 to 127, char stores only 7 bits of the data, 8th bits is used for sign representation.

Here is an example:

#include <stdio.h>
int main()
{
	char value=0;
	
	printf("Value is: %d\n",value);
	
	value=-128;
	printf("Value is: %d\n",value);
	
	value=127;
	printf("Value is: %d\n",value);
	
	return 0;	
}

Output

Value is: 0 
Value is: -128
Value is: 127





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.