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"?
C# 'secret' unveiled (it was just too good to be true)
Moderator: MaxCoderz Staff
-
- Calc King
- Posts: 1513
- Joined: Sat 05 Aug, 2006 7:22 am
C# 'secret' unveiled (it was just too good to be true)
Last edited by King Harold on Mon 30 Jun, 2008 8:40 am, edited 1 time in total.
- benryves
- Maxcoderz Staff
- Posts: 3089
- Joined: Thu 16 Dec, 2004 10:06 pm
- Location: Croydon, England
- Contact:
According to the C# Language Specification (page 205):
and:
In short: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.
Code: Select all
1 << -1
= 1 << (0xFFFFFFFF & 0x1F)
= 1 << 0x1F
= 1 << 31
= 0x80000000
Code: Select all
1 << -2
= 1 << (0xFFFFFFFE & 0x1F)
= 1 << 0x1E
= 1 << 30
= 0x40000000
-
- Calc King
- Posts: 1513
- Joined: Sat 05 Aug, 2006 7:22 am
-
- Calc King
- Posts: 1513
- Joined: Sat 05 Aug, 2006 7:22 am