COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### (int) -> (unsigned) -> (int) or (unsigned) -> (int) -> (unsigned): I'll loose something?

• Email
• Follow

```int x = <value>;
int y = (int)((unsigned)x);

The value of y is the same of x for any starting value and C
implementation?

unsigned int x = <value>;
unsigned int y = (unsigned)((int)x);

And in this case?

In other words, is there a risk to loose any value switching from
signed to unsigned and viceversa representation of integers?
```
 0

See related articles to this posting

```pozz <pozzugno@gmail.com> writes:

> int x = <value>;
> int y = (int)((unsigned)x);
>
> The value of y is the same of x for any starting value and C
> implementation?
>
> unsigned int x = <value>;
> unsigned int y = (unsigned)((int)x);
>
> And in this case?

Neither case is safe.  Both can involve an out-of-range conversion from
unsigned to int.  This is something that you might choose to live with.
In most cases the conversion is implementation defined[1] and will be
defined to do the "obvious" thing.

You can avoid a conversion by "type punning" using either a union or a
pointer conversion:

unsigned u = /* ... */;
int s = *(int *)&u;

This swaps the problem to one of representations.  Rather than relying
on the conversion of an out of range value you reply on there being no
unsigned int bit patterns that are not valid signed int representations.
I don't know of any implementations where this is a problem but it is
permitted (by 6.2.6.2 paragraph 2).

As I've alread posted, you can get round both issues if you really need
to.

<snip>

[1] The C standard includes permission to raise a signal but this is not
often done as far as I know.

--
Ben.
```
 0

```pozz wrote:
>
> int x = <value>;
> int y = (int)((unsigned)x);
>
> The value of y is the same of x for any starting value and C
> implementation?

If <value> is (-1),
then the value of (y) is equal to (int)UINT_MAX.

The value of UINT_MAX is implementation defined.

The value of (int)UINT_MAX may
again be implementation defined
depending on whether UINT_MAX is greater than INT_MAX.

Whether or not UINT_MAX is greater than INT_MAX,
is implementation defined.

--
pete
```
 0

```On 3/18/2011 6:06 AM, pozz wrote:
> int x =<value>;
> int y = (int)((unsigned)x);
>
> The value of y is the same of x for any starting value and C
> implementation?

No.  Suppose x is negative.  Since an unsigned value cannot be
negative, the (unsigned)x conversion produces a different value
UINT_MAX+x+1.  This value is quite likely to be larger than INT_MAX,
so converting it to plain int again produces an implementation-defined
result or raises an implementation-defined signal.

On most C implementations the "implementation-defined result"
turns out to be x, but that's not guaranteed by the language and
can't be counted on for "any" C implementation.

> unsigned int x =<value>;
> unsigned int y = (unsigned)((int)x);
>
> And in this case?

Similar problem: If the value of x is greater than INT_MAX,
converting that value to int is problematic.

> In other words, is there a risk to loose any value switching from
> signed to unsigned and viceversa representation of integers?

Yes.  (By the way, "vice versa" is a two-word phrase.  Also,
"loose" is a perfectly good verb, but it doesn't mean "lose.")

--
Eric Sosman
esosman@ieee-dot-org.invalid
```
 0

```On 18 Mar, 12:46, Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
> Neither case is safe. =A0Both can involve an out-of-range conversion from
> unsigned to int.

Hmm..., and what happens with printf, for example:
unsigned int x =3D UINT_MAX;
printf ("x=3D%u\n", x);

Is x converted to int (signed) when it is pushed onto the stack as an
argument for printf? Or maybe it is untouched onto the stack when the
parameter is one of the variable arguments (as happens in printf)?

```
 0

```On 18 Mar, 13:34, Eric Sosman <esos...@ieee-dot-org.invalid> wrote:
> > In other words, is there a risk to loose any value switching from
> > signed to unsigned and viceversa representation of integers?
>
> =A0 =A0 =A0Yes. =A0(By the way, "vice versa" is a two-word phrase. =A0Als=
o,
> "loose" is a perfectly good verb, but it doesn't mean "lose.")

I'm sorry, I don't know C language as English languange :-)
```
 0

```pozz <pozzugno@gmail.com> writes:

> On 18 Mar, 12:46, Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
>> Neither case is safe.  Both can involve an out-of-range conversion from
>> unsigned to int.
>
> Hmm..., and what happens with printf, for example:
>   unsigned int x = UINT_MAX;
>   printf ("x=%u\n", x);
>
> Is x converted to int (signed) when it is pushed onto the stack as an
> argument for printf? Or maybe it is untouched onto the stack when the
> parameter is one of the variable arguments (as happens in printf)?

No, you are passing an unsigned int not an it.  The default argument
promotions don't affect unsigned int.

--
Ben.
```
 0

```pozz <pozzugno@gmail.com> writes:
> On 18 Mar, 12:46, Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
>> Neither case is safe.  Both can involve an out-of-range conversion from
>> unsigned to int.
>
> Hmm..., and what happens with printf, for example:
>   unsigned int x = UINT_MAX;
>   printf ("x=%u\n", x);
>
> Is x converted to int (signed) when it is pushed onto the stack as an
> argument for printf? Or maybe it is untouched onto the stack when the
> parameter is one of the variable arguments (as happens in printf)?

No, there is no conversion and no problem.  The value of x is passed
as an argument to printf (this probably involves pushing it onto the
stack in most implementations, but the mechanism is irrelevant).
The "%u" tells printf to expect an unsigned argument -- which is
exactly what you gave it.  There's no int in sight (other than
the value returned by printf).

If you had used a "%d" format rather than "%u", then the behavior
would be undefined.  There would still be no *conversion*; instead,
printf would most likely try to interpret the passed unsigned
int value as if it were of type int.  The behavior is likely
to be what you'd expect, but the standard doesn't guarantee it.
(There's a special-case guarantee for the case where the value is
within the range of both types, but that doesn't apply here, since
UINT_MAX is outside the range of int.)

--
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
```
 0

```On Mar 18, 7:06=A0am, pozz <pozzu...@gmail.com> wrote:
> int x =3D <value>;
> int y =3D (int)((unsigned)x);
>
> The value of y is the same of x for any starting value and C
> implementation?
>
> unsigned int x =3D <value>;
> unsigned int y =3D (unsigned)((int)x);
>
> And in this case?
>
> In other words, is there a risk to loose any value switching from
> signed to unsigned and viceversa representation of integers?

No. There is no risk. Unsigned and signed integers are the same: they
only differ in how the sign bit is interpreted. y will be exactly x,
ALWAYS. If y was signed, on the other hand, the value could be
different (if and only if it was interpreted as negative, i.e. the
sign bit was set), but the binary content would be rigorously the
same. Even in the case that y were signed, (unsigned)y would be
exactly x. That's because since the binary content is not modified, a
conversion that in the end converts back to the original type will
mean exatcly the same thing.
```
 0

```puppi <fabricio.puppi@gmail.com> writes:
> On Mar 18, 7:06 am, pozz <pozzu...@gmail.com> wrote:
>> int x = <value>;
>> int y = (int)((unsigned)x);
>>
>> The value of y is the same of x for any starting value and C
>> implementation?
>>
>> unsigned int x = <value>;
>> unsigned int y = (unsigned)((int)x);
>>
>> And in this case?
>>
>> In other words, is there a risk to loose any value switching from
>> signed to unsigned and viceversa representation of integers?
>
> No. There is no risk. Unsigned and signed integers are the same: they
> only differ in how the sign bit is interpreted. y will be exactly x,
> ALWAYS. If y was signed, on the other hand, the value could be
> different (if and only if it was interpreted as negative, i.e. the
> sign bit was set), but the binary content would be rigorously the
> same. Even in the case that y were signed, (unsigned)y would be
> exactly x. That's because since the binary content is not modified, a
> conversion that in the end converts back to the original type will
> mean exatcly the same thing.

What you say is true for many (most) implementations, but it's not
at all guaranteed by the language.

Integer types can have padding bits and/or trap representations.
signed and unsigned int, for example, might not necessarily be
able to represent the same number of values; (signed) int might
have two different representations for zero.

--
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
```
 0

```On Mar 19, 11:14=A0pm, Keith Thompson <ks...@mib.org> wrote:
> puppi <fabricio.pu...@gmail.com> writes:
> > On Mar 18, 7:06=A0am, pozz <pozzu...@gmail.com> wrote:
> >> int x =3D <value>;
> >> int y =3D (int)((unsigned)x);
>
> >> The value of y is the same of x for any starting value and C
> >> implementation?
>
> >> unsigned int x =3D <value>;
> >> unsigned int y =3D (unsigned)((int)x);
>
> >> And in this case?
>
> >> In other words, is there a risk to loose any value switching from
> >> signed to unsigned and viceversa representation of integers?
>
> > No. There is no risk. Unsigned and signed integers are the same: they
> > only differ in how the sign bit is interpreted. y will be exactly x,
> > ALWAYS. If y was signed, on the other hand, the value could be
> > different (if and only if it was interpreted as negative, i.e. the
> > sign bit was set), but the binary content would be rigorously the
> > same. Even in the case that y were signed, (unsigned)y would be
> > exactly x. That's because since the binary content is not modified, a
> > conversion that in the end converts back to the original type will
> > mean exatcly the same thing.
>
> What you say is true for many (most) implementations, but it's not
> at all guaranteed by the language.
>
> Integer types can have padding bits and/or trap representations.
> signed and unsigned int, for example, might not necessarily be
> able to represent the same number of values; (signed) int might
> have two different representations for zero.
>
> --
> Keith Thompson (The_Other_Keith) ks...@mib.org =A0<http://www.ghoti.net/~=
kst>
> Nokia
> "We must do something. =A0This is something. =A0Therefore, we must do thi=
s."
> =A0 =A0 -- Antony Jay and Jonathan Lynn, "Yes Minister"

You're correct, of course. I was assuming that signed integers were
represented in two complement's form. Is there any (major) current
implementation that disagrees with that?
```
 0

```puppi <fabricio.puppi@gmail.com> writes:
> On Mar 19, 11:14 pm, Keith Thompson <ks...@mib.org> wrote:
[...]
>> What you say is true for many (most) implementations, but it's not
>> at all guaranteed by the language.
>>
>> Integer types can have padding bits and/or trap representations.
>> signed and unsigned int, for example, might not necessarily be
>> able to represent the same number of values; (signed) int might
>> have two different representations for zero.
>
> You're correct, of course. I was assuming that signed integers were
> represented in two complement's form.

You were also (implicitly) assuming that the most negative
representable value isn't treated as a trap representation, and
that unsigned-to-signed conversion for values exceeding INT_MAX
works as expected (it's implementation-defined).

>                                       Is there any (majorm) current
> implementation that disagrees with that?

I don't believe there are any conforming *hosted* implementations
that don't meet those assumptions.  There tends to be more variation
among freestanding implementations, but I don't know the details.

--
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
```
 0

```Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
> pozz <pozzu...@gmail.com> writes:
<snip>
> > unsigned int x =3D <value>;
> > unsigned int y =3D (unsigned)((int)x);
>
> Neither case is safe. =A0Both can involve an out-of-range
> conversion from unsigned to int.

More subtle is the case...

unsigned short x =3D USHRT_MAX;
unsigned short y =3D ++x;

The second initialisor expression can overflow if USHRT_MAX <=3D
INT_MAX. Since ++x is just shorthand for x =3D x + 1, the sub-
expression x + 1 can overflow if x is promoted to int and not
unsigned int. That can be true even if USHRT_MAX =3D=3D UINT_MAX in
the case where UINT_MAX =3D=3D INT_MAX.

--
Peter
```
 0

```Peter Nilsson <airia@acay.com.au> writes:

> Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
>> pozz <pozzu...@gmail.com> writes:
> <snip>
>> > unsigned int x = <value>;
>> > unsigned int y = (unsigned)((int)x);
>>
>> Neither case is safe.  Both can involve an out-of-range
>> conversion from unsigned to int.
>
> More subtle is the case...
>
>   unsigned short x = USHRT_MAX;
>   unsigned short y = ++x;
>
> The second initialisor expression can overflow if USHRT_MAX <=
> INT_MAX. [snip elaboration]

Presumably you mean ++x can overflow if USHRT_MAX == INT_MAX.
There is no overflow if USHRT_MAX < INT_MAX.
```
 0

13 Replies
249 Views

Similar Articles

12/12/2013 5:10:25 PM
[PageSpeed]

Similar Artilces:

doing something after so many times something has loaded
Hi am currently writing a java application. The program that i am writing allows people to be able log on to the program using a username and password. I want to be able to edit information in a MySQL Database when there has been a password error 3 times. How would i go about checking to see how many times something has happened. Any help would be apreciated. Thank you christopher_board@yahoo.co.uk writes: > Hi am currently writing a java application. The program that i am > writing allows people to be able log on to the program using a username > and password. I want to be able...

var Something= new Something() What does it mean ?
Hi, I was "studying" the famous (public code) BusyBox. I see the instruction: var busyBox = new BusyBox as in var busyBox = new BusyBox("BusyBox1", "busyBox", 4, "gears_ani_", ".gif", 125, 147, 206) What that syntax "var busyBox = new ... " actually means ?? What is NEW. I use all the time constructors in .NET, but I am unsure about Javascript. So far I have never seen it in javascript. Does it mean I can create an object with properties, fields, methods, etc ? -P pamelafluente@libero.it wrote: > What that syntax &quo...

how to do something
Hi, I've got two subroutines, one is saying 'do the other x times'. The other is checking records from a database and prints the x latest records. However, when a record matches something, it should be skipped. It all works, however, what happens is that the results are x - 1. So in the example underneath I normally get 3 results, except when \$vergelijker = jep, than the I only get 2 results, although I'd prefer 3. I tried this but it doesn't work: subroutine 1: my \$i = 2; for (0 .. \$i) { &html_recordheadline (&array_to_hash(\$_, @results)); } subroutine 2: (su...

How to find and replace something that is nested inside something else?
I am not sure if this group is the right place for this question but what I need is as follows. There is a piece of html. Throughout the html there are a lot of <br> tags. The task is to replace all these <br> tags with \n\r. The replacement must be performed only within <pre> blocks. I can do this using VBScript in the following way: Option Explicit dim path2folder : path2folder = "D:\" dim path2file : path2file = path2folder & "test.htm" dim fileResults : fileResults = path2folder & "test-results.txt" dim text dim regex Set regex...

Compiling on osx, something that might help and something not working still
Dear all, as usual it's a crazy mission to compile gnuplot on osx... Since it seems that it's a problem for many, here s my experience. I have installed a lot of libraries (pdflib, gdlib etc..) via fink Now, the last thing (I suppose introduced via Snow Leopard) is that we have to dd the architechure flag, so to compile, I have to configure like this: LDFLAGS=3D"-L/sw/lib -arch i386" CFLAGS=3D"-arch i386" ./configure -- prefix=3D/sw --disable-wxwidgets note that the first -L/sw/lib is just to force gnuplot to use the real fink readline and not the pr...

mysql how to erase something that is inside the tags <img>something</img> that is inside a column
mysql how to erase something that is inside the tags <img>something</ img> that is inside a column UPDATE jos_content SET title = REPLACE(title,'(<img>).+(</img>)','') but is not working please help On 29 Apr 2007 20:06:08 -0700, fhelik <fhelik@gmail.com> wrote: >mysql how to erase something that is inside the tags <img>something</ >img> that is inside a column >UPDATE jos_content SET title = REPLACE(title,'(<img>).+(</img>)','') > >but is not working > >please help I am a newbie my...

Bioware is up to something.
Just checked www.bioware.com , there's a "teaser" about the 4th October date. -Moa Dragon On Sun, 02 Oct 2005 14:05:09 +0200, Mils Michael <mickmils@tiscali.fr> wrote: >Just checked www.bioware.com , there's a "teaser" about the 4th >October date. > > >-Moa Dragon I did see this - http://www.bioware.com/games/dragon_age/ Is it new ? -- Bunnies aren't just cute like everybody supposes ! They got them hoppy legs and twitchy little noses ! And what's with all the carrots ? What do they need such good eyesight for anyway ? Bunnies...

something with a groove
hey people come have a try at my group.It's cool and fun even tough i'm the only member it's problems-at-homegooglegroups.com.weird name but it's a fun group were u can talk about anything.love nekeisha kittty said the following on 10/11/2005 7:01 PM: > hey people come have a try at my group.It's cool and fun even tough i'm > the only member it's problems-at-homegooglegroups.com.weird name but > it's a fun group were u can talk about anything.love nekeisha And who do you talk to since you are the only member? And, when you answer, who answers? Is i...

Something Esoteric...!!!
Here's something fun... http://transamoebae.blogspot.com/2005/11/pi-friendly-gematria.html TranslucentAmoebae wrote: > Here's something fun... > http://transamoebae.blogspot.com/2005/11/pi-friendly-gematria.html > fascinating ... ...

Something that is Majestic!!!!!!
Hey guys this new chess program looks phenomeal. I took a peek at the site and it is pretty impressive. This game seems pretty comparable to the well-known Chessmaster program since it is by the same creators. Anyways The In Game Intro Movie on the site is worth taking a look at, it really gives you a bold and fascinating view of the program!! http://www.majesticchess.com "gameloverfreak" <gamecutie2000@yahoo.com> wrote: > http://www.majesticchess.com Watching Vivendi Universal employees spam newsgroups is pretty majestic if you ask me. Seriously dude, smarten up befo...

did i do something wrong?
Hi I picked up a pile of sca 9gb WD drives for next to nothing, to go in a pile of scsi compaq pro 5100 stations to increase the 4gb drives fittied I bought 4 adapters, 3 like this SCA 80 pin to SCSI 1/2/3 68/50 Adapter Card http://cgi.ebay.co.uk/ws/eBayISAPI.dll?ViewItem&rd=1&item=6718897682&ssPageName=STRK:MEWN:IT 1 like this Ultra SCSI Adapter SCA 80 to 68 Pin Best Buy! http://cgi.ebay.co.uk/ws/eBayISAPI.dll?ViewItem&rd=1&item=5135539021&ssPageName=STRK:MEWN:IT the ultra worked fine but the others when the power is switched on causes smoke and burning. Shou...

Something I realized...
If everyone developed in Java, then all applications would run on all Oses...and look and behave exactly the same. It's not so much Windows vs. Linux, as Java versus Microsoft. -- The Texeme Construct, http://www.texeme.com 360, http://360.yahoo.com/manfrommars_43 On Sun, 02 Oct 2005 09:28:39 -0700, John Bailo <jabailo@texeme.com> wrote: > It's not so much Windows vs. Linux, as Java versus Microsoft. What a 1998 thing to say. -- -| Bob Hauck -| A proud member of the reality-based community. -| http://www.haucks.org/ On Sun, 02 Oct 2005 09:28:39 -0700, John Bail...

http://www.stickyminds.com/ -- _/\__/\__/\__/\__/\__/\_ www.huaonline.com My Homepage is my Castle ...

Something Missing
Something I've noticed missing from this group for months now, is people showing off anything that they might have made, created or done something with, with the NEW features in LW8? I remember at the beginning of the summer all the rage about all the cool things and hard body dynamics and soft body dynamics and other such things, and viewing all those really cool video samples posted at the NewTek web site showing them slicing the dress in half off of a lady and stitching cloth together all sorts of other outrageously cool things, yet I've yet to see any "real" life us...

Pattern for this? Or something?
Supposing I have two classes: class UIControl1 : public BaseControl1 {} class UIControl2 : public BaseControl2 {} where both base classes are not related between them. Then I'd like to -depending the user preference- use one of those controls. That is, I have to do this at runtime, depending on some flag set by the user of the program. Is there any way to relate these two classes? If they derived from the same (or related) base, then I would easily use that base class pointer, without worrying which class I'm using. But in this case, what can I do? TIA "notme" <a@b....

something for itertools
In a recent thread, http://mail.python.org/pipermail/python-list/2006-September/361512.html, a couple of very useful and enlightening itertools examples were given and was wondering if my problem also can be solved in an elegant way by itertools. I have a bunch of tuples with varying lengths and would like to have all of them the length of the maximal and pad with None's. So something like a = ( 1, 2, 3 ) b = ( 10, 20 ) c = ( 'x', 'y', 'z', 'e', 'f' ) should turn into a = ( 1, 2, 3, None, None ) b = ( 10, 20, None, None, None ) c = ( 'x',...

Have I missed something?
This is a multi-part message in MIME format. --------------060503030700080301030802 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit For a PL/1 news group there seems to be an awful lot of Fortran. Am I going to have to go back and update my Fortran skills? Before I was put on long term medical leave about eleven years ago, I either used PL/1 or Assembler. Before we acquired SAS, which is very PL/1 like, I did do some Fortran in order to use the Calcomp plotter. As a PL/1 user, maybe even bigot, I was considered to be a bit of wierdo. -- Paul...

Loose gunzip
I have some gzipped files downloaded from a server using a Perl program. Due to some problem, some files downloaded are corrupted. When we investigated further, we found that only two bytes ( in some random location) differ. Is there any way to loosely unzip that file to get whatever portion can be recovered. The file is a gzipped plain text file. vijay wrote: > I have some gzipped files downloaded from a server using a Perl > program. Due to some problem, some files downloaded are corrupted. When > we investigated further, we found that only two bytes ( in some random > location...

I have something bugs
Hello. I have something bugs, i am dummy in java.Source:import java.io.File;import java.io.FilenameFilter;public class Main { public static void main(String[] args) { File f = new File("C:\\Windows"); String[] strings = f.list( new FilenameFilter() { // throw exception public boolean accept(File arg0, String arg1) { if (new File(arg0.getAbsolutePath()).isDirectory()) return true; return false; } }); for (String value : strings) { System.out.println( value ); } }}simple scan directory. i must printing name of directory.but this code is printing all files and direc...

How to code something in Java
I'm still relatively new to Java. I have a data set in which each pairhas a number attached to it.Say the data set is {a,b,c,d,....z}Now form this data set, I have bunch of pairs and each pair has anumber attached to it.e.g. {a,b} = 3 {a,y} = 5I was wondering how will I code somethign like this in JavaIdeally I would have an array where I would have an input like Array[x][y].getValue()Any ideas.Thanks. On Nov 28, 3:36 pm, TheTravellingSalesman <saad.za...@gmail.com>wrote:> I'm still relatively new to Java. I have a data set in which each pair> has a number attached to...