Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signed and unsigned, and how bit extension works in C

Tags:

c

types

unsigned short s;
s = 0xffff;
int i = s;

How does the extension work here? 2 larger order bytes are added, but I'm confused whether 1's or 0's are extended there. This is probably platform dependent so let's focus on what Unix does. Would the two bigger order bytes of the int be filled with 1's or 0's, and why?

Basically, does the computer know that s is unsigned, and correctly assign 0's to the higher order bits of the int? So i is now 0x0000ffff? Or since ints are default signed in unix does it take the signed bit from s (a 1) and copy that to the higher order bytes?

like image 990
Tony Stark Avatar asked Dec 28 '22 18:12

Tony Stark


1 Answers

No, an unsigned value is never sign-extended. Upcasting will always pad such a value with zeroes.

More precisely, the unsigned variable represents a particular number, and it will still represent the same number after a cast, provided that is possible in the new format.

Hexadecimal or no, C (although not C99) and C++ are designed to work in the absence of bits, eg with base-10 numerics.

like image 68
Potatoswatter Avatar answered Jan 18 '23 14:01

Potatoswatter