• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 310
  • Last Modified:

Can function argument type char be typecasted to unsigned int?

Please consider following function definition:

/* write a new value into a dataword */
unsigned int replace_byte (unsigned int dataword, int bytenum,
  char byteval)


Can I typecast byteval as follows:
(unsigned int)byteval                    
         
If yes, what will be three most significant bytes of byteval after the typecasting.  Will they be zeros.
0
naseeam
Asked:
naseeam
  • 3
  • 2
2 Solutions
 
Infinity08Commented:
>> Can I typecast byteval as follows:

Yes.

>> If yes, what will be three most significant bytes of byteval after the typecasting.  Will they be zeros.

Since byteval is not unsigned, the 3 most significant bytes of the unsigned int will be all 1's if byteval was negative, and all 0's if it was positive.
0
 
Infinity08Commented:
To avoid that, use an unsigned char :

        unsigned int fun(unsigned char byteval) {
            return (unsigned int)byteval;
        }
0
 
Infinity08Commented:
>> To avoid that, use an unsigned char :

In that case, the 3 most significant bytes of the unsigned int will ALWAYS be all 0's.
0
 
evilrixSenior Software Engineer (Avast)Commented:
The result of typecasting a char to an unsigned int will depend upon whether the char was originally negative or positive. If it was positive all the unused MSBs will be 0 else they'll be set to F. This is, effectively, twos compliment.

i1      0x0000000a      unsigned int
i2      0xfffffff6      unsigned int

BTW: There is not need to explicitly cast char to unsigned int as it is an implicit conversion.

int main()
{
	char a = 10;
	unsigned int i1 = a;
	a = -10;
	unsigned int i2 = a;
 
	return 0;
}

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
NB. By MSBs I mean Most Significant Bytes  :)
0

Featured Post

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now