Click here to Skip to main content
15,908,673 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to implement 2 complement's from the value read from a textbox. How do I code it?

What I have tried:

C#
uint Ctrl_Pitch_Position = 0;

private void txtvehPitch_TextChanged(object sender, EventArgs e)
{
     Ctrl_Pitch_Position = Convert.ToUInt16(txtvehPitch.Text);
}
Posted
Updated 26-May-20 22:43pm
Comments
Richard MacCutchan 27-May-20 4:40am    
What exactly are you trying to do? You can complement a number quite simply by using the bitwise complement operator ~.

Firstly, don't use Convert on user input - always use TryParse instead, and report problems to the user instead of continuing. Users make mistakes: using Convert means your app crashes instead of behaving nicely and giving him a chance to fix the problem.

Two complement is easy though:
C#
UInt16 x = 666;
UInt16 Complement = (UInt16)~x;
 
Share this answer
 
In general it's better to use .Parse, see: How to convert a string to a number - C# Programming Guide | Microsoft Docs[^]

Additionally you can use Math.Round(), see: Math.Round Method (System) | Microsoft Docs[^]

As a non English speaker it is not exactly clear to me what you mean by "Complement", so Griffs answer might be what you want ...
 
Share this answer
 
v2
Comments
OriginalGriff 27-May-20 4:49am    
https://en.wikipedia.org/wiki/Two%27s_complement
May help. You almost certainly know it, just under a different name.
RickZeeland 27-May-20 4:55am    
Thanks, my compliments :)
OriginalGriff 27-May-20 5:07am    
And 2 you ... :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900