unsigned char vs uint8_t

Written By: Neilvert Noval - Jun• 10•12

Article Category: Geek

For C coders out there, there is a time in your programming life that you will come across this question: What data type to use? unsigned char? or uint8_t?

Let’s look at this example:




unsigned char VS uint8_t

Example: using unsigned char

We have our struct. It is actually a placeholder of parsed stream packets. The packet stream could be, for example

0x01 0x04 0xFF

With that, our struct can be filled up with

header = 0x01
controlByte = 0x04
breakProtocol = 0xFF

So what do we have here? The header, controlByte and breakProtocol are byte placeholder. And the programmer from example 1 made a point that he is storing 1 byte.




The Jury

There are rare cases that char is not equal to 1 byte just like Analog Devices 32-bit SHARC DSP. But it’s rare.

There’s nothing wrong with the code portrayed in example 1. However, giving the struct members with the type uint8_t is a self documentation to the code.

With uint8_t, the programmer have the intention that this placeholder accepts 1 byte (8 bits).

This is beneficial also to the one who reads the code because it is clear that the unit/type to store are numbers (uint8_t) and not characters (unsigned char).

Likewise, if the variable is expecting a character, it would be weird to have:

uint8_t firstCharacterOfTheTitle;

So it’s fitting to have

char firstCharacterOfTheTitle;

 

unsigned char vs uint8_t is a case-to-case basis. It depends on the intention of the programmer. It depends on what is actually stored on the variable. Though both have same size, but they differ on purpose.

FacebookLinkedInBlogger PostWordPressPinterestDiggRedditEmailTumblrShare

Related Posts:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


The author would love to read your comments.

Comments will appear once approved by the moderator.

2 Comments

  1. nemra says:

    Low-level programming (drivers, device interfacing, firmware, etc) usually is specific to the number of bits in their data types, so uses exact-width integer types like uintN_t.

    But if you are programming for a higher level and within a system, then you may not care the number of bits a char is, so char just represents a single character like ‘A’ or 1, but may not be 8 bits, although most systems this is 8-bits.

    uintN_t was introduced in the C99 standard to address these integer width issues and to make programs portable.

Leave a Reply

Your email address will not be published. Required fields are marked *


(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>