Jump to content

Welcome to Geeks to Go - Register now for FREE

Need help with your computer or device? Want to learn new tech skills? You're in the right place!
Geeks to Go is a friendly community of tech experts who can solve any problem you have. Just create a free account and post your question. Our volunteers will reply quickly and guide you through the steps. Don't let tech troubles stop you. Join Geeks to Go now and get the support you need!

How it Works Create Account
Photo

unable to explain how typecasting helps in getting proper value in add


  • Please log in to reply

#1
jfy143

jfy143

    New Member

  • Member
  • Pip
  • 3 posts
hi ,
please refer to the code below:

#include<stdio.h>

typedef unsigned char UInt8;
typedef unsigned short UInt16;
typedef unsigned long UInt32;
typedef unsigned long long UInt64;

int main(){
   
	UInt16 lowP = 8874, lowC =61008;
	UInt16 midP = 32566, midC =32848;
	UInt8 hiP = 0, hiC =0;

   //following two lines produce wrong output, note that we dont type cast midP and midC here
	UInt64 valP = lowP + (midP << 16) + (((unsigned long long)(hiP))<<32); //line 1
	UInt64 valC = lowC + (midC << 16) + (((unsigned long long)(hiC))<<32); //line 2

	//uncommenting below two lines instead of above two lines gives right result
	
   // UInt64 valP = lowP + (((unsigned long)midP) << 16) + (((unsigned long long)(hiP))<<32);
	//UInt64 valC = lowC + (((unsigned long)midC) << 16) + (((unsigned long long)(hiC))<<32);


	UInt64 diff = valC - valP;


	printf("valP:%x\n",valP >> 32); //print MSB 32 bits only
	printf("valC:%x\n",valC >> 32); //print MSB 32 bits only
	
	return 0;
}


now when I run this program I get following output:
valP:0
valC:ffffffff

However instead if I comment two lines mentioned as line1 and line2 and uncomment two lines
following in the code above, I get the following output:
valP:0
valC:0

Can somebody explain this behaviour?
Why sometimes I am getting 32bits MSB as all F sometimes though in code hiC is 0? And why timecasting micC to unsigned long
eradicate this problem?
I get most significant 32 bits as all F sometimes(for example with values in above code) when I dont typecast and I always get
as expected in case I typecast midC with unsigned long. Please explain.
  • 0

Advertisements







Similar Topics

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

As Featured On:

Microsoft Yahoo BBC MSN PC Magazine Washington Post HP