2 Replies - 20379 Views - Last Post: 26 February 2009 - 08:28 AM Rate Topic: -----

#1 alfred_w  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 26-February 09

What is u_char, u_short usef for? Why not use simply char and short..?

Posted 26 February 2009 - 12:37 AM

What is the use of u_char and u_short... etc ?
Is it possible to use char instead of u_char?
Is This A Good Question/Topic? 0
  • +

Replies To: What is u_char, u_short usef for? Why not use simply char and short..?

#2 born2c0de  Icon User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Re: What is u_char, u_short usef for? Why not use simply char and short..?

Posted 26 February 2009 - 05:50 AM

the u in u_char stands for unsigned.
The char data-type isn't always used to store characters. Since char is the only data type whose size is always 1 byte on any platform, it is used often to store 1 byte data.
1 byte can hold 255 values but the regular char datatype is a signed type and hence stores values from -127 to 127 i.e. After 127, the number is represented in 2's complement notation and hence the numbers are represented as negative.

To use only the values 0 to 255, the unsigned type is used. In this case, everything is considered as a positive number and 2's complement is not taken.
Was This Post Helpful? 0
  • +
  • -

#3 polymath  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 52
  • View blog
  • Posts: 670
  • Joined: 04-April 08

Re: What is u_char, u_short usef for? Why not use simply char and short..?

Posted 26 February 2009 - 08:28 AM

In case some don't know what twos compliment addition is:

A negative plus its absolute value is zero (in other words, -x + x =0). So given 1 in binary, how do you find its negative?

00000001
+ X
------------
00000000

If you invert all of the bits and add 1, you can get its negetive

00000001 (one)
11111111 (negative one)
----------------------------
00000000 (zero)

You simply add and carry the one across. The extra 1 at the end is not used because there are no more bits to carry over (the computer protects you from that- even if there are two variables next to eachother in memory).

So to find twos compliment negative of 7:

00000111 (seven)
11111001 (negative seven)
-----------------------------------
00000000 (zero)

It ends up that the leftmost bit hints the sign to you. This is how variables work for signed types. However, unsigned types give don't have negatives, so -7 (signed) above is 128+64+32+16+8+1=220 in unsigned notation.

That's as best as i can do for now. Hope this helps
Was This Post Helpful? 1

Page 1 of 1