• C

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.
LVL 1
naseeamAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.