473,566 Members | 2,770 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bit shifting past length of type

Is it a defined operation when I do something like this:
char a = 15;
a = a<<9;
Oct 2 '08 #1
12 2095
British0zzy said:
Is it a defined operation when I do something like this:
char a = 15;
a = a<<9;
Only on systems where char has at least 10 bits.

The relevant Standard cite is 3.3.7 Bitwise shift operators:

"If the value of the right operand is negative or is greater than or equal
to the width in bits of the promoted left operand, the behavior is
undefined."

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 2 '08 #2
Richard Heathfield wrote:
British0zzy said:
Is it a defined operation when I do something like this:
char a = 15;
a = a<<9;

Only on systems where char has at least 10 bits.

The relevant Standard cite is 3.3.7 Bitwise shift operators:

"If the value of the right operand is negative or is greater than or equal
to the width in bits of the promoted left operand, the behavior is
undefined."
Is there any system out there which will not zero out all the bits?
Oct 2 '08 #3
Richard Heathfield <r...@see.sig.i nvalidwrote:
British0zzy said:
Is it a defined operation when I do something like
this:
char a = 15;
a = a<<9;

Only on systems where char has at least 10 bits.

The relevant Standard cite is 3.3.7 Bitwise shift
operators:

"If the value of the right operand is negative or is
greater than or equal to the width in bits of the
promoted left operand, the behavior is undefined."
^^^^^^^^

That is almost incidental. The promoted type must have
a width of at least 16.

The problem is that plain char may be signed or
otherwise promote to a narrow int.

n1256: 6.5.7p4

The result of E1 << E2 is E1 left-shifted E2 bit
positions; vacated bits are filled with zeros. ...
If E1 has a signed type and nonnegative value,
and E1x2^E2 is representable in the result type,
then that is the resulting value; otherwise, the
behavior is undefined.

If CHAR_MAX == INT_MAX, then even a shift of 1
could invoke undefined behaviour.

There is also a problem with the assignment if the
shifted value _is_ representable as an int, but
outside the range of plain char.

Neither C90 nor C99 guarantee truncation for narrowing
of signed types. Under C99, an implementation defined
signal may even be raised.

As disasterous as this all sounds, the solution
is very simple. Where possible, stick to unsigned
types for bitwise operations. It is rarely impractical
to do this.

--
Peter
Oct 2 '08 #4
British0zzy <british0...@gm ail.comwrote:
Richard Heathfield wrote:
British0zzy said:
Is it a defined operation when I do something like
this:
char a = 15;
a = a<<9;

Is there any system out there which will not zero out
all the bits?
Why don't you state what you're trying to do, rather than
asking if code which you _think_ is the solution to an
(undisclosed problem) is valid?

You should be shifting unsigned types where possible.
It's unusual to shift wider than given type, but not
that unusual to shift _as wide_ as the given type.

If w is the width of an unsigned type, it's easy to
shift by 0..w bits, where a shift of w zeros out the
field...

/* shift by n bits: 0 <= n <= width of u */
if (w) u = u << (n - 1) << 1;

Note that 'width' means the number of (sign plus)
value bits, not necessarily the full size of the
type in bits.

--
Peter
Oct 2 '08 #5
British0zzy wrote:
Richard Heathfield wrote:
>British0zzy said:
>>Is it a defined operation when I do something like this:
char a = 15;
a = a<<9;
Only on systems where char has at least 10 bits.
The value of CHAR_BIT doesn't matter, not directly. The
expression is evaluated this way:

- First, the starting value of `a' is converted from `char'
to `int' (on most systems) or `unsigned int' (on some).
The statement is now equivalent to one of `a = 15 << 9;'
or `a = 15u << 9;'.

- Next, the shift operator is applied. The numerical result
is within the range of both `int' and `unsigned int', so
now we have either `a = 7680;' or `a = 7680u;'.

- Now comes the dodgy part: The result of the shift is
converted from `int' or `unsigned int' to `char'. If
If `char' is unsigned, all is well: the conversion
yields `7680 % (CHAR_MAX+1)', mathematically speaking.
If `char' is signed and if CHAR_MAX >= 7680 (implying
CHAR_BIT >= 14), all is well again and the conversion
yields `(char)7680'. It's the remaining case that makes
trouble: if `char' is signed and CHAR_MAX < 7680, the
conversion takes us into poorly-charted waters, either
yielding an implementation-defined result or raising an
implementation-defined signal.

- Finally (if we get this far), the converted value is
stored in `a'.

So, yes: The value of CHAR_BIT affects the outcome because
it affects the value of CHAR_MAX used in the conversion, but it
does not affect the operation of or validity of the shift. To
illustrate, changing the second line to `int i = a << 9;' yields
a fragment whose behavior is the same on all implementations .

--
Eric Sosman
es*****@ieee-dot-org.invalid
Oct 2 '08 #6
Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
British0zzy said:
char a = 15;
a = a<<9;

...The value of CHAR_BIT affects the outcome because
it affects the value of CHAR_MAX used in the conversion,
but it does not affect the operation of or validity of
the shift.

... changing the second line to `int i = a << 9;'
yields a fragment whose behavior is the same on all
implementations .
If CHAR_MAX <= INT_MAX and a (INT_MAX >9), then the
behaviour of a << 9 is undefined.

--
Peter
Oct 2 '08 #7
British0zzy wrote:
>
Is it a defined operation when I do something like this:
char a = 15;
a = a<<9;
That depends on the value of MAX_CHAR. Compare it with 512 * 15.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Oct 2 '08 #8
In article
<f8************ *************** *******@k7g2000 hsd.googlegroup s.com>, Peter
Nilsson <ai***@acay.com .auwrote:

[...]
If w is the width of an unsigned type, it's easy to
shift by 0..w bits, where a shift of w zeros out the
field...

/* shift by n bits: 0 <= n <= width of u */
if (w) u = u << (n - 1) << 1;

Note that 'width' means the number of (sign plus)
value bits, not necessarily the full size of the
type in bits.
Even though the comment claims that n can be 0, the code causes UB for n=0
due to n-1. Even if the n-1 issue is solved, you still have the
unconditional shift left by 1 to deal with. How about something like

int halfn = n >1;
u << halfn << (n-halfn)

which then allows n to be up to w*2-1?
Oct 2 '08 #9
CBFalconer <cbfalco...@yah oo.comwrote:
British0zzy wrote:
Is it a defined operation when I do something like
this:
* char a = 15;
* a = a<<9;

That depends on the value of MAX_CHAR.
ITYM CHAR_MAX
*Compare it with 512 * 15.
--
Peter
Oct 3 '08 #10

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

Similar topics

6
4384
by: David Stockwell | last post by:
Hi, My background is c/c++ and java. I'm learning python at this point. My question is does python share java's peculiar mode of bit shifting, or does python adhere closer to c's bit shifting? in java there are 3 kinds of bit shifts: << (shift left) >> (preserve the sign bit as we move right ) >>> (0 filled on the left as we...
9
8702
by: GGG | last post by:
Noticed something odd in the way bit shifting was working today. As far as I have ever heard, shifting will shift in zeros(signed ints aside) However I foudn something odd when I am shifting exactly the number of bits in a value... i.e. uint32_t x = 5;
0
1677
by: Rick Slansky | last post by:
Hi: This should be a fairly simple page, which lines up the second row cell nicely in the lower right corner. It does in Netscape, but when I check the page in Explorer, that cell (the entire cell, not just the contents) is shifted down by 6 to 8 pixels. I would appreciate any help in identifying why the alignment difference is happening...
8
1643
by: Nick Patavalis | last post by:
Ok, what is this supposed to print: #include <stdio.h> #include <stdint.h> int main (void) { uint32_t r, s;
20
15141
by: Xenos | last post by:
Can anyone tell me what the standard says about using fseek (on a binary file) to seek past the end-of-file? I can't find anything in my (draft) copy of the standard, nor in the FAQ. Thanks
2
2043
by: salsipius | last post by:
Can someone please help me clarify the below code. I think the shifting has to do with converting datatypes and/or loss of data but am not really clear on the details, could you help shed some light please? // Allocate array for( i = 0; i < Length; i++ ) { //pArray_00 is a BYTE Array -- Here a cast is used because
10
10672
by: krunalb | last post by:
Hi, I am trying to shift unsigned long long value by 64 bits and this is what i get #include <stdio.h> int main() { unsigned short shiftby= 64;
4
1858
by: Neil | last post by:
I previously posted about data shifting between records in my Access 2000 MDB with a SQL Server 7 back end, using ODBC linked tables. Every once in a while, data from one record mysteriously appears in another record. This incident happened again, this time adding a new wrinkle to the situation. There are two tables -- TableA and TableB --...
8
1534
by: manu | last post by:
Hi All, I have executed the below program and got 0x1f as output... Can anyone explain me why this output is coming instead of zero? Compiler - gcc int main() {
0
7666
marktang
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...
0
7584
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...
0
7888
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. ...
0
8108
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...
0
7951
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...
0
5213
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...
0
3643
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...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1201
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.