How the unsigned to signed integet conversion is done ?
For eg:
unsigned int ui = 100;
int si = ui;
What will be the value if "si" is printed ? How this conversion
is done ?
Thanx for any help in advance ....
Nov 15 '05
19 2078
"Alexei A. Frounze" wrote:
.... snip ... Shamefully, but I had to fix a few bugs in my recent code... The code was something like this:
typedef uint unsigned int;
void drawlineh (int x, int y, uint len, uint color) { if (x+len < 0) return; // the rest of code that's properly working... }
The problem is that x gets converted to unsigned int in the expression "x+len" and hence for negative x I wouldn't have the desired return from the function.
You can eliminate any positive values of x in the first place:
if ((x < 0) && (-x < len)) return;
else {
...
}
--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
On Tue, 09 Aug 2005 00:56:12 +0000, CBFalconer wrote: "Alexei A. Frounze" wrote: ... snip ... Shamefully, but I had to fix a few bugs in my recent code... The code was something like this:
typedef uint unsigned int;
void drawlineh (int x, int y, uint len, uint color) { if (x+len < 0) return; // the rest of code that's properly working... }
The problem is that x gets converted to unsigned int in the expression "x+len" and hence for negative x I wouldn't have the desired return from the function.
You can eliminate any positive values of x in the first place:
if ((x < 0) && (-x < len)) return; else { ... }
That could still fail i.e. when x < -INT_MAX. Try
if ((x < 0) && (x+len >= len)) return;
This assumes that x+len isn't mathematically greater than UINT_MAX as does
the original.
Small challenge: when could x+len == len ? The code rules out x==0.
Lawrence
Lawrence Kirby wrote: CBFalconer wrote: "Alexei A. Frounze" wrote: ... typedef uint unsigned int;
void drawlineh (int x, int y, uint len, uint color) { if (x+len < 0) return; if ((x < 0) && (-x < len)) return;
That could still fail i.e. when x < -INT_MAX. Try
if ((x < 0) && (x+len >= len)) return;
This assumes that x+len isn't mathematically greater than UINT_MAX
Not sure what you mean here since, if x is negative and len is
positive,
then x+len can't 'mathematically ' be greater than len, let alone
UINT_MAX.
as does the original. Small challenge: when could x+len == len ? The code rules out x==0.
Spoiler: When x is INT_MIN, len = 0, and INT_MIN == 0u.
The last condition occurs when...
INT_MAX == UINT_MAX && INT_MIN == -INT_MAX - 1
I.e. a twos complement system where the most negative int value is not
a trap representation, and the sign bit of an int is a padding bit in
the unsigned int representation.
--
Peter
"Alexei A. Frounze" <al*****@chat.r u> writes: There's one more problem related to what's being discussed in "find out the problem" by me and others... It's all about the conversion. Shamefully, but I had to fix a few bugs in my recent code... The code was something like this:
typedef uint unsigned int;
I guess you meant ``typedef unsigned int uint'' here.
void drawlineh (int x, int y, uint len, uint color) { if (x+len < 0) return; // the rest of code that's properly working... }
The problem is that x gets converted to unsigned int in the expression "x+len" and hence for negative x I wouldn't have the desired return from the function. This is really an annoying feature of C... The only way to make it work w/o changing the API (i.e. making len of type int too) is to do a cast:
if (x+(int)len < 0) return;
Unfortunately, then there are cases when you lose precision; i.e. when
INT_MAX < UINT_MAX, which is usually the case (at least, on all the
machines I've worked with).
On Mon, 8 Aug 2005 23:32:34 +0100, Chris Croughton
<ch***@keristor .net> wrote: On Tue, 9 Aug 2005 00:44:30 +0400, Alexei A. Frounze <al*****@chat.r u> wrote:
<snip> But different people find different parts of [assembly] counter-intuitive, that's the problem, and same is true for all other programming languages. Including asssembler.
NOT R1 BIC R1, R0
instead of
AND R1, R0
And many other oddities which only make sense if you know a particular processor in detail.
The only ISA I know with BIC is PDP-11, in which case the first insn
should be _COM_.
But on the PDP-8 (except models with EAE) you had AND but not IOR (or
XOR/EOR) so had to construct it with something like:
CLA ; clear accumulator (can omit in some cases where known clear)
TAD x ; 2sComplement add, the only kind available
AND y
CIA ; 1sComplement then increment accumulator = 2sC negate
TAD x
TAD y
; x plus y minus (x and y) = x ior y
or x plus y minus 2 times (x and y) = x xor y
(where the 2 times can be done using rotate-left)
<snip> If I were to change C, I'd change the conversions/promotions to be more math-like, not C-like. But that's not going to happen anytime soon. Sigh.
And would confuse many more. C was written for systems programmers, largely, and so was designed tro do what you told it and nothing more. So if you want to do some conversions other than the default, you do them. C is not designed for mathematics (try FORTRAN -- "FORmula TRANslation"), so you get 1/2 == 0 because that is what is expected in integer arithmetic even though it isn't in mathematics, and if you then assign the result to a floating point variable it sets it to zero.
Although FORTRAN is the same here -- type of a (sub)expression
including a literal is independent of context. In fact 3 / 4 gives 0
is probably as frequently asked (relatively) on comp.lang.fortr an as
here, although dblvar = 3.1415926536 ! loses precision is more
frequent, since floating literals default to single precision in Ftn
not double as in C, and _some_ Ftn compilers "helpfully" fix this in
_some_ (simpler) cases whereas I have heard of no C compilers that do.
- David.Thompson1 at worldnet.att.ne t
"Chris Croughton" <ch***@keristor .net> wrote in message
news:sl******** **********@ccse rver.keris.net. .. On Tue, 9 Aug 2005 00:44:30 +0400, Alexei A. Frounze <al*****@chat.r u> wrote:
Shamefully, but I had to fix a few bugs in my recent code... The code
was something like this:
typedef uint unsigned int;
void drawlineh (int x, int y, uint len, uint color) { if (x+len < 0) return; // the rest of code that's properly working... }
The problem is that x gets converted to unsigned int in the expression "x+len" and hence for negative x I wouldn't have the desired return from
the function. Several popular compilers will warn you about that if you enable warnings, because the condition can never be true so the statements after it are unreachable.
This is really an annoying feature of C... The only way to make it work
w/o changing the API (i.e. making len of type int too) is to do a cast:
if (x+(int)len < 0) return;
If that's what you mean then do it -- but if len is larger than MAXINT it will have undefined effect so you need to check for that first.
Yep. The ugly thing gets in. That makes me love asm more and more. Asm is the simplest programming language ever -- I always know what the code does and I know that for
all bugs and problems it's me to blame. :)
And is totally non-portable. Even between assemblers for the same platform.
True, but for an experienced programmer such as I am, converting most of the
source between TASM, MASM, NASM, (G)AS, etc etc, isn't a problem, rather a
straightforward excersize. But C is such a wonderful creature, no surprise so many people get it all wrong. They have always been
getting it wrong and they continue to do so. At times it's so counter intuitive
for an HLL.
But different people find different parts of it counter-intuitive, that's the problem, and same is true for all other programming languages. Including asssembler.
NOT R1 BIC R1, R0
instead of
AND R1, R0
While I understand what NOT and AND usually mean and do, BIC isn't in my
vocabulary. What is it? BIt Clear, clears the specified pattern of bits?
I'm not sure I see the point here other than doing essentially the same
thing two slightly different ways.
And many other oddities which only make sense if you know a particular processor in detail.
That's fine :) If I were to change C, I'd change the conversions/promotions to be more math-like, not C-like. But that's not going to happen anytime soon.
Sigh. And would confuse many more. C was written for systems programmers, largely, and so was designed tro do what you told it and nothing more.
That's how every language and machine work. All errors are commited by the
engineers because when they fail translate the idea/algorithm into machine
language. I don't see a problem here. Actually, having both signed and
unsigned integer types in any language would be that "more" thing as most
CPUs don't differentiate the two, it's not needed in 2's complemented
addition, subtraction, comparison... The CPU simply sets/clears the carry
and overflow flags and it is the programmer to give the meaning to these
flags and sign bits. The sign starts matter when we do conversion to longer
types (as it needs replication) and in multiply/divide/modulo operations.
The rest, the bit logic, is the bit logic, it shouldn't and doesn't care
about the meanings of the MSBits.
So if you want to do some conversions other than the default, you do them. C is not designed for mathematics (try FORTRAN -- "FORmula TRANslation"), so you get 1/2 == 0 because that is what is expected in integer arithmetic even though it isn't in mathematics, and if you then assign the result to a floating point variable it sets it to zero.
That's fine. Actually, any decent mathematicion must understand this.
It's certainly not perfect, at least one of the original authors of the language has admitted that the precedence of some of the operators was wrong,
like in:
if (a & b == c) {}
?
:)
but there is by now no chance of changing it because there is too much code which depends on it. Just as with natural language, we can't just change English spelling to something more lojikal at a wim, evn tho sum pepl hav trid to do that.
Wel, if ju rimuv ol thi unnidid nd komplikeitid stuf from thi langwidj, it'l
bicum unridbl. Or turn in to something closer to, say, German. :)
Except it's worse with computer languages because you can probably understand what I wrote where a compiler can't...
Ah stupid compilers... :) There's a joke in our company... Q: how to make
such code, adding to which -10 dB of noise (or 32% of errors/bugs:), would
still compile and work properly?
(And yes, I know that the Cyrillic alphabet did have several letters removed as an act of the government, but that can only be done when the government can say that all books in the previous script have to be replaced and be obeyed...)
If that was done to English, the world would benefit. But it can't be done
because the price would IMO be even bigger contextuality. Currently, at
least the spellings of different things are different. Can't imagine they
would be identical. The whole language would need changes.
Alex
"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org... "Alexei A. Frounze" <al*****@chat.r u> writes: "Old Wolf" <ol*****@inspir e.net.nz> wrote in message news:11******** **************@ o13g2000cwo.goo glegroups.com.. . [...] So how would you compare -2000000000 and +3000000000 in ASM, without something at least as complicated as you would do in C ?
At least I would know about it for sure, w/o special books and standards
:) There are no special books for assembly language?
There are. But there you know what you're dealing with. But C appears to
most easy, at least at first glance. And that's a dangerous imagination that
leads to bugs, since at first many wouldn't go into such subtle details and
would either omit the important parts or not even have them in the C book at
all, which is no surprise to me now. There used to be plenty of bad writers.
Am I the only who feels uncomfortable with certain aspects of C? Or is
there anyone who understands a bit of my concerns?
I'd be suspicious of anyone who *wasn't* uncomfortable with some aspects of C. K&R themselves (or at least K and/or R) have expressed misgivings about some of the design choices.
:) That gives me some confidence.
Alex
"CBFalconer " <cb********@yah oo.com> wrote in message
news:42******** *******@yahoo.c om... "Alexei A. Frounze" wrote:
.... typedef uint unsigned int;
void drawlineh (int x, int y, uint len, uint color) { if (x+len < 0) return; // the rest of code that's properly working... }
The problem is that x gets converted to unsigned int in the expression "x+len" and hence for negative x I wouldn't have the desired return from the function.
You can eliminate any positive values of x in the first place:
if ((x < 0) && (-x < len)) return; else { ... }
No, both negative and non-negative values are allowed for x, and len can be
any positive or 0.
That's exactly what I expect them to be. But I see what you mean...
(x+len < 0) can be transformed in two cases:
x >= 0: the original condition is always false
x < 0: the original condition can be turned into:
((x < 0) && (-x > len))
You put the wrong inequality sign (because (x+len<0) is equivalent to
(len<-x) -- you get it by subtracting x from both sides).
OK, this one is definetely better, though not ideal anyway. :)
Alex
"Giorgos Keramidas" <ke******@ceid. upatras.gr> wrote in message
news:86******** ****@gothmog.gr ... "Alexei A. Frounze" <al*****@chat.r u> writes:
.... typedef uint unsigned int;
I guess you meant ``typedef unsigned int uint'' here.
Sure. void drawlineh (int x, int y, uint len, uint color) { if (x+len < 0) return; // the rest of code that's properly working... }
The problem is that x gets converted to unsigned int in the expression "x+len" and hence for negative x I wouldn't have the desired return from the function. This is really an annoying feature of C... The only way to make it work w/o changing the API (i.e. making len of type int too) is to do a cast:
if (x+(int)len < 0) return;
Unfortunately, then there are cases when you lose precision; i.e. when INT_MAX < UINT_MAX, which is usually the case (at least, on all the machines I've worked with).
As long as the above condition (after fixing it) tests correctly, there
should be no loss of any precision.
Alex
"Dave Thompson" <da************ *@worldnet.att. net> wrote in message
news:hq******** *************** *********@4ax.c om...
.... The only ISA I know with BIC is PDP-11, in which case the first insn should be _COM_.
But on the PDP-8 (except models with EAE) you had AND but not IOR (or XOR/EOR) so had to construct it with something like: CLA ; clear accumulator (can omit in some cases where known clear) TAD x ; 2sComplement add, the only kind available AND y CIA ; 1sComplement then increment accumulator = 2sC negate TAD x TAD y ; x plus y minus (x and y) = x ior y
or x plus y minus 2 times (x and y) = x xor y (where the 2 times can be done using rotate-left)
(x | y) == ~((~x) & (~y))
and:
(x & y) == ~((~x) | (~y))
which was named after De Morgan, if I'm not mistaken.
and
(x ^ y) == ((~x)&y) | (x&(~y)) ==
[
((~x)&y) == ~(x|(~y))
(x&(~y)) == ~((~x)|y)
]
== (~(x|(~y))) | (~((~x)|y)) through ORs and inversion only
or
== ~((~(~x)&y)) & (~(x&(~y))) through ANDs and inversion only
Indeed, one may use addition/subtraction to convert between &, |, and ^:
x+y == (x&y)+(x|y)
and it's easy to see the correctness of the above: if at a given bit
position the bits of x and y aren't both ones, the above is obviosly true:
(0&1)+(0|1)==1 , (0&0)+(0|0)==0 . If they're both ones, then (1&1)+(1|1)==1+ 1.
It should not be hard to prove the form with exclusive OR too:
x+y == 2*(x&y)+(x^y). It's easy to see that (x&y)+(x^y) is identical to
(x&y)+(x|y), when the bits of x and y at the same bit position aren't both
ones. If they are both ones, a compensation is due. And it can be made by
adding another (x&y) term.
And, of course, it's easy to see that (x&y)+(x^y) == x|y.
Alex This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: MiniDisc_2k2 |
last post by:
Okay, here's a question about the standard. What does it say about
unsigned/signed mismatches in a comparison statement:
char a = 3;
unsigned char b = 255;
if (a<b)
Now what's the real answer here? If a is converted to unsigned, then b>a.
But, if b is converted to signed,then a>b. What's the correct coversion
(what is the compiler supposed to do?)
|
by: John Harrison |
last post by:
I knew that unsigned integral data types were the cause of scads of mostly
spurious warning messages, but I didn't realise that they were a security
risk too (see here
http://www.securitytracker.com/alerts/2004/Feb/1009067.html). All for one
measly extra bit.
So has the time come for C++ to deprecate unsigned integral types?
john
|
by: Rade |
last post by:
Following a discussion on another thread here... I have tried to understand
what is actually standardized in C++ regarding the representing of integers
(signed and unsigned) and their conversions. The reference should be 3.9.1
(Fundamental types), and 4.7 (Integral conversions).
It seems to me that the Standard doesn't specify:
1) The "value representation" of any of these types, except that (3.9.1/3)
"... The range of nonnegative...
|
by: Peter Piper |
last post by:
A Quick question if someone could help, im sure this has been asked
before, but googling is getting me now where slowly.
Is it possible to get an unsigned 32 bit integer field in Access.
Im storing IP address in their integer form (ie. 32 bits) and Long
Integer because it is signed can not represent the full range needed
(0..4294967295), neither can Double.
Any suggestions please?
|
by: TTroy |
last post by:
Hello, I'm relatively new to C and have gone through more than 4 books
on it. None mentioned anything about integral promotion, arithmetic
conversion, value preserving and unsigned preserving. And K&R2
mentions "signed extension" everywhere.
Reading some old clc posts, I've beginning to realize that these books
are over-generalizing the topic. I am just wondering what the
difference between the following pairs of terms are:
1)...
| |
by: luke |
last post by:
Hi everybody,
please, can someone explain me this behaviour.
I have the following piece of code:
long long ll;
unsigned int i = 2;
ll = -1 * i;
printf("%lld\n", ll);
|
by: techie |
last post by:
I have defined a number of unsigned integer types as follows:
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedfe long long uint64;
Is it necessary to explicitly cast from one type of unsigned integer type to
another even though they do so implicitly?
|
by: somenath |
last post by:
Hi All,
I am trying to undestand "Type Conversions" from K&R book.I am not
able to understand the
bellow mentioned text
"Conversion rules are more complicated when unsigned operands are
involved. The problem
is that comparisons between signed and unsigned values are machine-
dependent, because
they depend on the sizes of the various integer types. For example,
suppose that int is 16 bits
|
by: Kislay |
last post by:
Consider the following code snippet
unsigned int i=10;
int j= - 2; // minus 2
if(i>j)
cout<<"i is greater";
else
cout<<"j is greater";
Since i is unsigned , j is greater . I know why , but vaguely . Can
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |