473,785 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

mixing signed and unsigned

I have a problem. I want to compare an integral value, n, against three
half open ranges as follows

[-A, 0) // range 1
[0, B) // range 2
[B, C} // range 3

Each range corresponds to a different outcome and if the integral value
isn't within any of the ranges, that's a fourth outcome. So far so easy,
the problem is that n is a signed quantity and A, B, C are unsigned
quantities. Apart from this obscure corner of my code this makes perfect
sense, so I don't want to change the signedness of anything.

How to I write these tests so that my code is reasonably understandable,
rather than a horrible mess of casts and compiler warnings?

One more point, of the unsigned quantity, only B is guaranteed small
enough that it could be safely cast to a signed integer.

john
Feb 17 '07 #1
26 2778
John Harrison wrote:
I have a problem. I want to compare an integral value, n, against three
half open ranges as follows

[-A, 0) // range 1
[0, B) // range 2
[B, C} // range 3

Each range corresponds to a different outcome and if the integral value
isn't within any of the ranges, that's a fourth outcome. So far so easy,
the problem is that n is a signed quantity and A, B, C are unsigned
quantities. Apart from this obscure corner of my code this makes perfect
sense, so I don't want to change the signedness of anything.

How to I write these tests so that my code is reasonably understandable,
rather than a horrible mess of casts and compiler warnings?

One more point, of the unsigned quantity, only B is guaranteed small
enough that it could be safely cast to a signed integer.
Use the next size up, int64_t?

--
Ian Collins.
Feb 17 '07 #2
Ian Collins wrote:
John Harrison wrote:
>>I have a problem. I want to compare an integral value, n, against three
half open ranges as follows

[-A, 0) // range 1
[0, B) // range 2
[B, C} // range 3

Each range corresponds to a different outcome and if the integral value
isn't within any of the ranges, that's a fourth outcome. So far so easy,
the problem is that n is a signed quantity and A, B, C are unsigned
quantities. Apart from this obscure corner of my code this makes perfect
sense, so I don't want to change the signedness of anything.

How to I write these tests so that my code is reasonably understandable,
rather than a horrible mess of casts and compiler warnings?

One more point, of the unsigned quantity, only B is guaranteed small
enough that it could be safely cast to a signed integer.

Use the next size up, int64_t?
Well a further problem is that the signed type is ptrdiff_t and the
unsigned type is size_t. So I can't say what the next size up is, or
even if it exists.

In the past I've ranted against the very existance of unsigned types on
this group. I promise I'll repent if someone can show me an elegant way
to do this.

john
Feb 17 '07 #3
>
In the past I've ranted against the very existance of unsigned types on
this group. I promise I'll repent if someone can show me an elegant way
to do this.

john
Answering my own question here, but this is the best I've come up with

if (A <= std::numeric_li mits<ptrdiff_t> ::max() &&
n < -static_cast<ptr diff_t>(A))
{
// out of range
}
else if (n < 0)
{
// range 1
}
else if (n < static_cast<ptr diff_t><(B))
{
// range 2
}
else if (C <= std::numeric_li mits<ptrdiff_t> ::max() &&
n < static_cast<ptr diff_t>(C))
{
// range 3
}
else
{
// out of range
}

Not quite a bad as I feared but still pretty ugly.

john
Feb 17 '07 #4
John Harrison wrote:
>>
In the past I've ranted against the very existance of unsigned types
on this group. I promise I'll repent if someone can show me an elegant
way to do this.

john


Answering my own question here, but this is the best I've come up with

if (A <= std::numeric_li mits<ptrdiff_t> ::max() &&
n < -static_cast<ptr diff_t>(A))
{
// out of range
}
else if (n < 0)
{
// range 1
}
else if (n < static_cast<ptr diff_t><(B))
{
// range 2
}
else if (C <= std::numeric_li mits<ptrdiff_t> ::max() &&
n < static_cast<ptr diff_t>(C))
{
// range 3
}
else
{
// out of range
}

Not quite a bad as I feared but still pretty ugly.

john
Spoke too soon, here's the corrected version with a couple more casts

if (A <= static_cast<siz e_t>(std::numer ic_limits<ptrdi ff_t>::max())
&& n < -static_cast<ptr diff_t>(A))
{
// out of range
}
else if (n < 0)
{
// range 1
}
else if (n < static_cast<ptr diff_t>(B))
{
// range 2
}
else if (C <= static_cast<siz e_t>(std::numer ic_limits<ptrdi ff_t>::max())
&& n < static_cast<ptr diff_t>(C))
{
// range 3
}
else
{
// out of range
}

john
Feb 17 '07 #5
John Harrison wrote:
John Harrison wrote:
>>>

if (A <= static_cast<siz e_t>(std::numer ic_limits<ptrdi ff_t>::max())
&& n < -static_cast<ptr diff_t>(A))
{
// out of range
}
else if (n < 0)
{
// range 1
}
else if (n < static_cast<ptr diff_t>(B))
{
// range 2
}
else if (C <= static_cast<siz e_t>(std::numer ic_limits<ptrdi ff_t>::max())
&& n < static_cast<ptr diff_t>(C))
{
// range 3
}
else
{
// out of range
}

john
Yet another correction. Just proves how horrible this signed/unsigned
stuff is, or am I missing a trick?

else if (C static_cast<siz e_t>(std::numer ic_limits<ptrdi ff_t>::max())
|| n < static_cast<ptr diff_t>(C))

john
Feb 17 '07 #6
John Harrison wrote:
I have a problem. I want to compare an integral value, n, against three
half open ranges as follows

[-A, 0) // range 1
[0, B) // range 2
[B, C} // range 3

Each range corresponds to a different outcome and if the integral value
isn't within any of the ranges, that's a fourth outcome. So far so easy,
the problem is that n is a signed quantity and A, B, C are unsigned
quantities. Apart from this obscure corner of my code this makes perfect
sense, so I don't want to change the signedness of anything.

How to I write these tests so that my code is reasonably understandable,
rather than a horrible mess of casts and compiler warnings?

One more point, of the unsigned quantity, only B is guaranteed small
enough that it could be safely cast to a signed integer.
What about:

#include <iostream>

int main ( void ) {
unsigned long A = 30;
unsigned long B = 20;
unsigned long C = 100;
long x = 0;
while ( std::cin >x ) {
if ( x >= 0 ) {
if ( x < B ) {
std::cout << "range 2";
} else if ( x < C ) {
std::cout << "range 3";
} else {
std::cout << "above all ranges";
}
} else {
if ( ( -x ) <= A ) {
std::cout << "range 1";
} else {
std::cout << "below all ranges";
}
}
std::cout << '\n';
}
}

This only compares positive values. As long as the unsigned type is large
enough to represent the absolute values of the signed type, you will be
fine.
Best

Kai-Uwe Bux
Feb 17 '07 #7
John Harrison wrote:
I have a problem. I want to compare an integral value, n, against three
half open ranges as follows

[-A, 0) // range 1
[0, B) // range 2
[B, C} // range 3

Each range corresponds to a different outcome and if the integral value
isn't within any of the ranges, that's a fourth outcome. So far so easy,
the problem is that n is a signed quantity and A, B, C are unsigned
quantities. Apart from this obscure corner of my code this makes perfect
sense, so I don't want to change the signedness of anything.

How to I write these tests so that my code is reasonably understandable,
rather than a horrible mess of casts and compiler warnings?

One more point, of the unsigned quantity, only B is guaranteed small
enough that it could be safely cast to a signed integer.
In that case, the values of the range limits need to be adjusted. If A
is greater than INT_MAX, replace it with INT_MAX. Same for C. Then do
everything signed.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Feb 18 '07 #8
In article <3w************ ******@newsfe2-gui.ntli.net>,
jo************* @hotmail.com says...
I have a problem. I want to compare an integral value, n, against three
half open ranges as follows

[-A, 0) // range 1
[0, B) // range 2
[B, C} // range 3

Each range corresponds to a different outcome and if the integral value
isn't within any of the ranges, that's a fourth outcome. So far so easy,
the problem is that n is a signed quantity and A, B, C are unsigned
quantities. Apart from this obscure corner of my code this makes perfect
sense, so I don't want to change the signedness of anything.

How to I write these tests so that my code is reasonably understandable,
rather than a horrible mess of casts and compiler warnings?

One more point, of the unsigned quantity, only B is guaranteed small
enough that it could be safely cast to a signed integer.
If you can't count on having a type with a large enough range to hold
all the possible values, you probably need to work primarily with
unsigned values:

bool in_range_u(ptrd iff_t value, size_t min, size_t max) {
if (value < 0)
return false;
return (static_cast<si ze_t>(value) >= min) &&
(static_cast<si ze_t>(value) < max);
}

if (in_range_u(x, 0, B))
first_range();
else if (in_range_u(-x, 0, A+1)
second_range();
else if (in_range_u(x, B, C)
third_range();
else
fourth_range();

The two casts aren't really necessary, but I'd prefer them over a
warning, which would be normal for a mixed signed/unsigned comparsison.

Although I believe the code should work, it is _quite_ fragile. For
example in_range_u(-x, 0, A+1) does NOT really work correctly. We get
around that by testing the second range first, and only testing the
first range if we've determined that x!=0.

To be pedantically correct, you might need to add special case code for
a couple of possibilities: one is for magnitude(A) == magnitude
(INT_MIN), and the other is for A==std::numeric _limits<size_t> ::max. It
isn't hard to do these without warnings or casts, but it does make the
code a bit ugly.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Feb 18 '07 #9
Kai-Uwe Bux wrote:
John Harrison wrote:

>>I have a problem. I want to compare an integral value, n, against three
half open ranges as follows

[-A, 0) // range 1
[0, B) // range 2
[B, C} // range 3

Each range corresponds to a different outcome and if the integral value
isn't within any of the ranges, that's a fourth outcome. So far so easy,
the problem is that n is a signed quantity and A, B, C are unsigned
quantities. Apart from this obscure corner of my code this makes perfect
sense, so I don't want to change the signedness of anything.

How to I write these tests so that my code is reasonably understandable,
rather than a horrible mess of casts and compiler warnings?

One more point, of the unsigned quantity, only B is guaranteed small
enough that it could be safely cast to a signed integer.


What about:

#include <iostream>

int main ( void ) {
unsigned long A = 30;
unsigned long B = 20;
unsigned long C = 100;
long x = 0;
while ( std::cin >x ) {
if ( x >= 0 ) {
if ( x < B ) {
std::cout << "range 2";
} else if ( x < C ) {
std::cout << "range 3";
} else {
std::cout << "above all ranges";
}
} else {
if ( ( -x ) <= A ) {
std::cout << "range 1";
} else {
std::cout << "below all ranges";
}
}
std::cout << '\n';
}
}

This only compares positive values. As long as the unsigned type is large
enough to represent the absolute values of the signed type, you will be
fine.
I thought of something like that, but two problems.

-x would overflow if x == std::numeric_li mits<ptrdiff_t> ::min()

"above all" and "below all" are the same outcome and I'd prefer not to
write the same code twice

john
Feb 18 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
15664
by: tinesan | last post by:
Hello fellow C programmers, I'm just learning to program with C, and I'm wondering what the difference between signed and unsigned char is. To me there seems to be no difference, and the standard doesn't even care what a normal char is (because signed and unsigned have equal behavior). For example if someone does this: unsigned char a = -2; /* or = 254 */
3
406
by: T | last post by:
Given: typedef unsigned short u16; typedef signed int i32; u16 u0 = 0xFFFF; i32 i1 = u0; u16 u1 = 0; i32 i2 = u1 - (u16)1;
10
3310
by: =?iso-8859-2?B?SmFuIFJpbmdvuQ==?= | last post by:
Hello everybody, this is my first post to a newsgroup at all. I would like to get some feedback on one proposal I am thinking about: --- begin of proposal --- Proposal to add signed/unsigned modifier to class declarations to next revision of C++ programming language
7
5049
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
6
6458
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
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
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...
0
10148
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10091
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,...
0
9950
tracyyun
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...
0
8972
agi2029
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...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.