C# 'secret' unveiled (it was just too good to be true)

Feel like posting Off Topic? Do it here.

Moderator: MaxCoderz Staff

Post Reply
King Harold
Calc King
Posts: 1513
Joined: Sat 05 Aug, 2006 7:22 am

C# 'secret' unveiled (it was just too good to be true)

Post by King Harold »

If this is somewhere else on the internet.. ok fine
But I personally discovered it independently anyway

The trick is:
shifting by a negative amount will rotate instead!
example:
1 << -1 = 0x80000000
1 << -2 = 0x40000000
etc

very useful

this also makes C# one of the few high level languages with rotation build in, although, is it really "build in"?
Last edited by King Harold on Mon 30 Jun, 2008 8:40 am, edited 1 time in total.
User avatar
benryves
Maxcoderz Staff
Posts: 3087
Joined: Thu 16 Dec, 2004 10:06 pm
Location: Croydon, England
Contact:

Post by benryves »

According to the C# Language Specification (page 205):
For the predefined operators, the number of bits to shift is computed as follows:
  • When the type of x is int or uint, the shift count is given by the low-order five bits of count. In other words, the shift count is computed from count & 0x1F.
  • When the type of x is long or ulong, the shift count is given by the low-order six bits of count. In other words, the shift count is computed from count & 0x3F.
In short:

Code: Select all

  1 << -1
= 1 << (0xFFFFFFFF & 0x1F)
= 1 << 0x1F
= 1 << 31
= 0x80000000
and:

Code: Select all

  1 << -2
= 1 << (0xFFFFFFFE & 0x1F)
= 1 << 0x1E
= 1 << 30
= 0x40000000
King Harold
Calc King
Posts: 1513
Joined: Sat 05 Aug, 2006 7:22 am

Post by King Harold »

Do we have a coincidence here?
It also worked with all other numbers I tried..
Probably just didn't try enough
User avatar
benryves
Maxcoderz Staff
Posts: 3087
Joined: Thu 16 Dec, 2004 10:06 pm
Location: Croydon, England
Contact:

Post by benryves »

Even if the behaviour is a little odd, it's still only shifting. 2<<-1 shifts 31 places, resulting in 0, not 1 (as you'd expect from rotation).
King Harold
Calc King
Posts: 1513
Joined: Sat 05 Aug, 2006 7:22 am

Post by King Harold »

Actually, it's not even odd
It makes the translation to native code easier

pity, it really looked like it was rotating..
User avatar
benryves
Maxcoderz Staff
Posts: 3087
Joined: Thu 16 Dec, 2004 10:06 pm
Location: Croydon, England
Contact:

Post by benryves »

"Odd" in the sense that people might expect 1<<x where x > 31 to always return zero, rather than return 1<<(x&0x1F).

I don't know of any high-level languages that support rotation, and only one language that differentiates between arithmetic and logical shifts (ECMAScript: >> vs. >>>).
User avatar
Dwedit
Maxcoderz Staff
Posts: 579
Joined: Wed 15 Dec, 2004 6:06 am
Location: Chicago!
Contact:

Post by Dwedit »

I there's a language called C-- which supports rotations.
You know your hexadecimal output routine is broken when it displays the character 'G'.
Post Reply