473,804 Members | 2,277 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

regarding << and >> operators

#include<stdio. h>
int main(void){
printf("%d %d\n",32<<1,32< <0);
printf("%d %d\n",32<<-1,32<<-0);
<----------------------------------see here
printf("%d %d\n",32>>1,32> >0);
printf("%d %d\n",32>>-1,32>>-0);
<----------------------------------and here

return 0;
}

$ make
gcc -Wall -g -o test test.c
test.c: In function `main':
test.c:4: warning: left shift count is negative
test.c:6: warning: right shift count is negative
$ ./test
64 32
0 32 (1)
16 32
0 32 (2)

Why 0 is printed in (1) and (2) ??

Nov 15 '06 #1
10 2004
In article <11************ **********@m7g2 000cwm.googlegr oups.com>,
onkar <on*******@gmai l.comwrote:
printf("%d %d\n",32<<-1,32<<-0);
printf("%d %d\n",32>>-1,32>>-0);
>0 32 (1)
>0 32 (2)
>Why 0 is printed in (1) and (2) ??
You got lucky and it printed out something that you recognize
immediately as being odd. If you had been less lucky, it might have
printed something you were expecting, and you might have then tried
to use the operation in a real program only to discover much too late
that your code was incorrect.

To phrase the above in a blunter form: *any* answer would have been
right, because the result of left or right shifting by a negative
value is undefined in C (as is the result of shifting by more than
the number of bits in the promoted value.)

--
If you lie to the compiler, it will get its revenge. -- Henry Spencer
Nov 15 '06 #2

onkar wrote:
#include<stdio. h>
int main(void){
printf("%d %d\n",32<<1,32< <0);
printf("%d %d\n",32<<-1,32<<-0);
<----------------------------------see here
printf("%d %d\n",32>>1,32> >0);
printf("%d %d\n",32>>-1,32>>-0);
<----------------------------------and here

return 0;
}

$ make
gcc -Wall -g -o test test.c
test.c: In function `main':
test.c:4: warning: left shift count is negative
test.c:6: warning: right shift count is negative
$ ./test
64 32
0 32 (1)
16 32
0 32 (2)

Why 0 is printed in (1) and (2) ??
Shifting by a negative value is undefined in standard C and also
nonsensical.

Nov 15 '06 #3
santosh wrote:
Shifting by a negative value is undefined in standard C
Yes.
and also nonsensical.
No.

It has an obvious meaning, and one that has been implemented
in at least one machine and at least one programming language.

(So acting on vague memory I googled "vax negative shift" and got
to the interesting http://yarchive.net/comp/shift_instruction.html.
I still haven't managed to recover the langaueg I remember with
neg-shits-t'other-way ...)

--
Chris "hantwig efferko VOOM!" Dollin
Nit-picking is best done among friends.

Nov 15 '06 #4
In article <ej**********@m urdoch.hpl.hp.c om>,
Chris Dollin <ch**********@h p.comwrote:
>Shifting by a negative value is undefined in standard C
[...]
>and also nonsensical.
>No.

It has an obvious meaning, and one that has been implemented
in at least one machine and at least one programming language.
And since the definition of shifting in the standard is in terms of
multiplication or division by 2^N, it would be natural to extend it to
negative shifts.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Nov 15 '06 #5
Chris Dollin wrote:
santosh wrote:
Shifting by a negative value is undefined in standard C

Yes.
and also nonsensical.

No.

It has an obvious meaning, and one that has been implemented
in at least one machine and at least one programming language.

(So acting on vague memory I googled "vax negative shift" and got
to the interesting http://yarchive.net/comp/shift_instruction.html.
I still haven't managed to recover the langaueg I remember with
neg-shits-t'other-way ...)
Interesting link. Straight from the horse's mouth too. I'll be sure to
read it later. Thanks.

Nov 15 '06 #6
Chris Dollin wrote:
santosh wrote:
>Shifting by a negative value is undefined in standard C

Yes.
>and also nonsensical.

No.

It has an obvious meaning, and one that has been implemented
in at least one machine and at least one programming language.
[OT] At the machine level, by giving meaning to negative shift
counts, you can implement a complete set of shifts with only two
instructions: ArithShift and LogicalShift. Two more are needed to
implement rotations. Double the count if you also need to
implement "through carry". One actual shift instruction with a 3
bit detail field will do it all.
[/OT]

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Nov 15 '06 #7
Richard Tobin wrote:
>
In article <ej**********@m urdoch.hpl.hp.c om>,
Chris Dollin <ch**********@h p.comwrote:
Shifting by a negative value is undefined in standard C
[...]
and also nonsensical.
No.

It has an obvious meaning, and one that has been implemented
in at least one machine and at least one programming language.

And since the definition of shifting in the standard is in terms of
multiplication or division by 2^N, it would be natural to extend it to
negative shifts.
But, what happens when the hardware includes bit-shift operators,
and the hardware itself assumes an unsigned shift value? If C were
to say "negative shifts mean shift in the opposite direction", then
every non-constant shift would have to convert:

x << y

to the equivalent of:

( y < 0 ) ? (x >-y) : (x << y)

(Without the issue of side-effects, of course.)

Hardly an efficient operator, is it?

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Nov 15 '06 #8
In article <45************ ***@spamcop.net >,
Kenneth Brody <ke******@spamc op.netwrote:
>And since the definition of shifting in the standard is in terms of
multiplicati on or division by 2^N, it would be natural to extend it to
negative shifts.
>But, what happens when the hardware includes bit-shift operators,
and the hardware itself assumes an unsigned shift value?
I was giving the matural extensibility of the definition as further
evidence against the nonsensicality of negative shifts, not as an
argument for having them in C. The efficiency argument is,
unfortunately, overwhelming.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Nov 15 '06 #9
In article <45************ ***@yahoo.com>
CBFalconer <cb********@mai neline.netwrote :
>[OT] At the machine level, by giving meaning to negative shift
counts, you can implement a complete set of shifts with only two
instructions : ArithShift and LogicalShift. Two more are needed to
implement rotations. Double the count if you also need to
implement "through carry". One actual shift instruction with a 3
bit detail field will do it all.
[/OT]
There is a much better way to do the whole thing, using an
extra argument. Consider the following ASCII-art diagram of
an 8-bit "shifter" (larger variants are obvious, but harder to
draw :-) ):

val1 val2
ABCDEFGH ijklmnop
\\\ /////
\\\ /////
||||||||
FGHijklm
result

If val1==0, bits A-H are all-zeros, and this computes val2 >3,
with val2 unsigned ("logical" shift).

If val1==-1, bits A-H are all-ones, and this computes val2 >3,
with val2 signed and its sign bit set ("arithmetic " shift).

If val2==0, bits i-p are all-zeros, and this computes val1 << 5.

If val1==val2, bits F-H are the same as bits n-p, and this computes
(val1 rotateleft 5) or, equivalently, (val2 rotateright 3).

If neither val1 nor val2 is all-zeros or all-ones, and not equal to
each other, this extracts an 8-bit sub-field from two 8-bit values.

The diagram above is of a "funnel shifter", which has three inputs
and one output. The inputs are two values (of some bit-size), and
a bit-index in the range [0..N-1], where N is the number of bits
in the values. (The instruction-set designer must decide whether
the "count" above is 3 or 5; either is OK.)

Note that a single 64-bit funnel shifter can implement 8, 16, or
32-bit shifts and rotates; you just have to arrange for the bits
to be shifted-or-rotated to be in the uppermost and lowermost bits
of the two "value" inputs, then choose the shift count correctly.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 15 '06 #10

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

Similar topics

44
3386
by: seberino | last post by:
Tuples are defined with regards to parentheses ()'s as everyone knows. This causes confusion for 1 item tuples since (5) can be interpreted as a tuple OR as the number 5 in a mathematical expression such as x = (5) * (4+6). Wouldn't it have been better to define tuples with <>'s or {}'s or something else to avoid this confusion?? Perhaps ()'s are a good idea for some other reason I don't know?
2
10572
by: Donald Firesmith | last post by:
I am having trouble having Google Adsense code stored in XSL converted properly into HTML. The <> unfortunately become &lt; and &gt; and then no longer work. XSL code is: <script type="text/javascript"> <!]> </script> <script type="text/javascript"
1
1335
by: PengYu.UT | last post by:
I heard that != >= > <= operators are defined based on the operator == <. Could you tell me which header file defines the four operators? Best wishes, Peng
8
1570
by: Greenhorn | last post by:
Hi, Those relational operators have operands of all numerical type int,char,float etc. They also are working for character arrays. Whats the logic behind their working. Is the length of the array compared first and then each character compared with corresponding character. { const char msg = "msessage}", ch = "Za";
1
2045
by: ±èÀçȲ | last post by:
//this code generates the error. uint a=1,b=2; Console.WriteLine(a << b); Console.WriteLine(a >> b); What problem does "uint type" have.?
5
2418
by: Suman | last post by:
Having had a look at the C++ FAQ, comp.lang.c++ & comp.std.c++ archives and Stroustrup's FAQs (particularly the following: <url:http://www.research.att.com/~bs/bs_faq2.html#overload-dot/>) I am left to wondering why Stroustrup doesn't mention the *_cast<> operators or operator .* in that particular FAQ. Archived discussions have convinced me that .* _cannot_ be overloaded. I have gathered a notion (perhaps incorrectly) that the *_cast<>...
3
3389
by: ajay2552 | last post by:
Hi, I have a query. All html tags start with < and end with >. Suppose i want to display either '<' or '>' or say some text like '<Company>' in html how do i do it? One method is to use &lt, &gt ,&ltCompany&gt to display '<', '>' and '<Company>' respectively. But is there any freeware code available which could implement the above functionality without having to use &gt,&lt and such stuff???
3
2946
by: newbie | last post by:
Same thing g++ complains when using hash_map<>, but is happy with map<--I understand hahs_map is not standardized, but since the compiler didn't complain something like 'hash_map<not defined', I suppose it's supported and should behave well when I used it correctly. BUT it didn't. Here is my code snippet: class MyKey { public: virtual void foo() { return; }
2
1282
by: defn noob | last post by:
What does >and << do? Googling on them and they are just ignored...
0
10346
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
10347
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
10090
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
9173
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...
1
7635
isladogs
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...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
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
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.