[Question]
  [
# Background
The [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight) of an integer is the number of ones in its binary representation. For this challenge, integers are represented with 32 bits, and they are unsigned.
# Challenge
Given an integer between 0 and 2^32-1 (non-inclusive), output a *different* integer within the same range, and also with the same Hamming weight.
# Examples
```
Input (Decimal) | Input (Binary) | Hamming weight | Possible output (Decimal)
       46       |   0b0010 1110  |       4        |      15
       12       |   0b0000 1100  |       2        |      3
        1       |   0b0000 0001  |       1        |      2
        3       |   0b0000 0011  |       2        |      6
      2^31      |   0b1000....0  |       1        |      1
      2^31+2    |   0b1000...10  |       2        |      3
      2^32-5    |   0b1111..011  |       31       |      2^31-1
      2^32-2    |   0b1111....0  |       31       |      2^31-1
        0       |   0b0000 0000  |       0        | None (This case need not be handled)
      2^32-1    |   0b1111....1  |       32       | None (This case need not be handled)
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution in the fewest bytes in each language wins.
  
[Answer]
# x86-64 assembly, ~~5~~ 4 bytes
```
   0:   97                      xchg   %eax,%edi
   1:   d1 c0                   rol    %eax
   3:   c3                      retq   
```
A function using the C calling convention that bitwise rotates its argument left by 1 bit.
[Answer]
# Python, 20 bytes
```
lambda x:x*2%~-2**32
```
Bitwise rotation left by 1 bit.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
32&B1YSXB
```
Circularly shifts the 32-digit binary representation one step to the right.
[Try it online!](https://tio.run/##y00syfn/39hIzckwMjjC6f9/QwA "MATL – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes
```
‘&~^^N&$
```
Swaps the least significant set and unset bit.
[Try it online!](https://tio.run/##y0rNyan8//9Rwwy1urg4PzWV/0f3HG5/1LRG4eGO7Y8a5ihEZRYoZOYVlJYoJOalKJRkpCoUpRaX5pQUK@Sngbk5mXnZegqPGuYqHNqqYK3kFAzUrIJkgGNBQSpUp0dibm5mXrpCeWpmekZJMUSX@///JmY6CoZGOgpGWlrGRrpAhqGOgjGEawgA "Jelly – Try It Online")
### How it works
```
‘&~^^N&$  Main link. Argument: n
‘         Increment; yield n+1, toggling all trailing set bits and the rightmost
          unset bit.
  ~       Bitwise NOT; yield ~n, toggling ALL bits of n.
 &        Bitwise AND; yield (n+1)&~n, keeping the only bit that differs in n+1 and
          ~n, i.e., the rightmost unset bit.
   ^      Perform bitwise XOR with n, toggling the rightmost unset bit.
       $  Combine the two links to the left into a monadic chain.
     N        Negate; yield -n. Since ~n = -(n+1) in 2's complement, -n = ~n+1.
      &       Take the bitwise AND of n and -n. Since -n = ~n + 1 and n = ~~n, the
              same reasoning that applied for (n+1)&~n applies to -n&n; it yields
              the rightmost unset bit of ~n, i.e., the rightmost set bit of n.
    ^      XOR the result to the left with the result to the right, toggling the
           rightmost set bit of the left one.
```
[Answer]
## JavaScript (ES6), ~~35~~ 31 bytes
Looks for the first bit transition (0 → 1 or 1 → 0) and inverts it.
```
f=(n,k=3)=>(n&k)%k?n^k:f(n,k*2)
```
### Demo
```
f=(n,k=3)=>(n&k)%k?n^k:f(n,k*2)
;[ 46, 12, 255, 2**32-2 ]
.map(n => {
  r = f(n);
  console.log((n >>> 0), '=', (n >>> 0).toString(2), '-->', (r >>> 0), '=', (r >>> 0).toString(2));
})
```
## Bit rotation, 14 bytes
Much shorter but less fun.
```
n=>n>>>31|n<<1
```
### Demo
```
let f =
n=>n>>>31|n<<1
;[ 46, 12, 255, 2**32-2 ]
.map(n => {
  r = f(n);
  console.log((n >>> 0), '=', (n >>> 0).toString(2), '-->', (r >>> 0), '=', (r >>> 0).toString(2));
})
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 78 bytes
```
(([()()])[[]()]){((){}<({({})({}())}{})>)}{}([(({}(({}){})())<>)]){({}())<>}{}
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0MjWkNTQzNWMzo6FkRVa2hoVtfaaFRrVNdqArGGpmYtkGUHIoFKQSIgGZCkpqaNHVgHWJWNHVDF//9GhibmJhbGZiYWAA "Brain-Flak – Try It Online")
Returns 2n if n < 2^31, and 2n+1-2^32 otherwise. Unfortunately, because Brain-Flak doesn't have any fast way to determine the sign of a number, the program times out on TIO if the input differs from 2^31 by more than about 500000.
### Explanation
First, push -2^32 onto the stack:
```
(([()()])[[]()])                               push (initial value) -2 and (iterator) -5
                {((){}<                >)}     do 5 times:
                       ({({})({}())}{})        replace the current (negative) value with the negation of its square
                                            {}   pop the (now zero) iterator
```
Then, compute the desired output:
```
      (({}){})                        replace n by 2n on left stack
   ({}        ())                     push 2n+1-2^32 on left stack
  (              <>)                  push again on right stack
([                  ])                push its negation on right stack
                      {({}())<>}      add 1 to the top value of each stack until one of them reaches zero
                                {}    pop this zero, and implicitly print the number below it on the stack
```
[Answer]
# dc, 10
```
?2~z31^*+p
```
[Try it online](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnYGKmYGikYGJkaWJpZg4kFaoN9fQMDWqtFVLyuRSAoKAoM68kTUFJtVhB105BSUEFphssm5qckY8QUqhRSElW0E1VUP9vb1RXZWwYp6Vd8F@dKyU/L/U/AA).
This is an arithmetic implementation of a 32bit right-rotate:
```
?           # input
 2~         # divmod by 2 - quotient pushed first, then the remainder
   z        # z pushes the size of the stack which will be 2 (quotient and remainder) ...
    31^     #  ... and take that 2 to the 31st power
       *    # multiply the remainder by 2^31
        +   # add
         p  # output
```
[Answer]
# APL, 12 bytes
```
(2⊥32⍴1)|2×⊢
```
**How?**
```
           ⊢  ⍝ monadic argument
         2×   ⍝ shift left (×2)
(2⊥32⍴1)|     ⍝ modulo 2^32 - 1
```
[Answer]
# Java 8, ~~117~~ ~~17~~ 29 bytes
```
n->n*2%~-(long)Math.pow(2,32)
```
+12 bytes by changing `int` to `long`, because `int`'s max size is `2³¹-1`
~~100~~ 89 bytes saved by creating a port of [*@AndersKaseorg*'s amazing Python answer](https://codegolf.stackexchange.com/a/124087/52210).
[Try it here.](https://tio.run/##zZO9TsMwFIX3PMVRJCSbEos6bfmJYGBup25FDMYNxSW9jhK3qEXh1YNNOiABc@rBV74@555PlrxWO5XYMqf18q3VhaprzJShjwgw5PLqRekci3AECksraDYNhXjme03kt9opZzQWOOAOLSX3dC7PPhMW5Hym3Kso7TuTF6nkbRYM5fa58Iajb2fNEhufyeauMrR6fILiPwKNnzqaTLPvznxfu3wj7NaJ0otdQcxggBgs9iWQCWcfDKlq301jhod7fosgOAh9bPxv6DSdK@ZdbGAYyhNg6B8hPYFXuPSrf4yb66vJeNQ/x6@PhnTI@6f6A0t6XQLZI1sTNe0X)
Outputs:
```
46 (101110):                                     92 (1011100)
12 (1100):                                       24 (11000)
1 (1):                                           2 (10)
3 (11):                                          6 (110)
10000 (10011100010000):                          20000 (100111000100000)
987654 (11110001001000000110):                   1975308 (111100010010000001100)
2147483648 (10000000000000000000000000000000):   1 (1)
4294967294 (11111111111111111111111111111110):   4294967293 (11111111111111111111111111111101)
```
**Old answer (~~117~~ 118 bytes):**
```
n->{long r=0;for(;!n.toBinaryString(++r).replace("0","").equals(n.toBinaryString(n).replace("0",""))|r==n;);return r;}
```
+1 byte by changing `int` to `long`, because `int`'s max size is `2³¹-1`
[Try it here.](https://tio.run/##zZPBUsIwEIbvPMWaUzLQAAVRydSDZzjhCcdDLAEDJalpigPYZ69J24Mjei457E7@/Lv5NjPZ8gMPdCrUdrUr44RnGcy5VOcOgFRWmDWPBSz9FiDRagMxnvmkCHNa0XEhs9zKGJZwgghKFTyeK6OJBmytDWY3ilr9JBU3x4U1Um1wt2sINSJNXHOMBqiHEKHiI@dJhi/M6sJKvkwUKUaYETY3CgwrSuZJ0vwtcSQN0EHLFezdMLju9PIKnPyYRDrc8WTGKmVxzKzYU51bmjqzTRSW0AUEGLnkR/7NJYk/J1PwhhONG@H/gtpTVyFSX@sZhuEVMLSPMLqCVxi41T7Gw/3d5HbcPgf234TMuX2nqf7EYQ9GQ9IqVRX6fXjmO5GB1br6ydNGrpj/gA5dlwBC1thaYS86RfkN)
Outputs:
```
46 (101110):                                     15 (1111)
12 (1100):                                       3 (11)
1 (1):                                           2 (10)
3 (11):                                          5 (101)
10000 (10011100010000):                          31 (11111)
987654 (11110001001000000110):                   255 (11111111)
2147483648 (10000000000000000000000000000000):   1 (1)
```
[Answer]
## Mathematica, 29 bytes
```
Mod@##+Quotient@##&[2#,2^32]&
```
[Try it at the Wolfram sandbox](https://sandbox.open.wolframcloud.com/)
Rotates left arithmetically: first multiply by 2, which possibly shifts the number out of range, then cut off the out-of-range digit with `Mod[...,2^32]` and add it back on the right with `+Quotient[...,2^32]`.
(Mathematica does have a single builtin that gives the modulus and the quotient in one go, but it's `QuotientRemainder`, which is a bit of a golfing handicap…)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
·žJ<%
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0Paj@7xsVP//NzGyNLE0MzeyNAYA "05AB1E – Try It Online")
**Explanation**
Uses the trick to rotate the binary representation left by 1 bit from [Anders Kaseorg's python answer](https://codegolf.stackexchange.com/a/124087/47066).
```
·       # input * 2
    %   # modulus
 žJ<    # 2^32-1
```
[Answer]
## R, ~~42~~ 63 bytes
```
function(x){s=x;while(s==x){sample(binaryLogic::as.binary(x))}}
```
Shuffles the bits around randomly, but checks to make sure it didn't return the same number by chance.
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~81~~ 80 bytes
(1 byte saved thanks to @Ørjan Johansen reminding me dup is shorter than push 0)
```
   
 
 	
					 
    	 
	 		
	 
   	        
 
 	  
 
 	  
	   
  
   	 
	 	 	
 	
```
[Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIAgIgxanACRQCczkVoACsDkFxgoWgSkAagIYocP7/b2RoYm5iYWxmYg4A "Whitespace – Try It Online")
Basically implements a cyclic right bitshift using integer arithmetic. Pushing a large constant is expensive in Whitespace so we save some bytes by pushing 2^8 and squaring it twice. (Saves 1 byte over (2^16)^2 and 10 bytes over pushing 2^32 directly.)
## Explanation
```
sssn  ; push 0
sns   ; dup
tntt  ; getnum from stdio
ttt   ; retrieve n from heap and put it on the stack
sns   ; dup
ssstsn ; push 2
tstt  ; mod - check if divisible by 2 (i.e. even)
ntsn  ; jez "even"
ssstssssssssn ; push 2^8
sns   ; dup
tssn  ; mul - square it to get 2^16
sns   ; dup
tssn  ; mul - square it to get 2^32
tsss  ; add 2^32 so MSB ends up set after the divide
nssn  ; even:
ssstsn ; push 2
tsts  ; divide by 2, aka shift right
tnst  ; putnum - display result
```
[Answer]
# Python 2.7, 89 bytes
Full Program:
```
from random import*;a=list(bin(input())[2:].zfill(32));shuffle(a);print int(''.join(a),2)
```
[Try it online!](https://tio.run/##DcsxDsIwDEDRq3SrjaBDQAxEnKRiMKVRjFI7St2B3rtzyPD1pp9/FlVcraHo0hWST4OXrMVOnp6JV4M3C7DkzQBxdI/XsAdOCa4O0a9xCyHNQOhzYbGuBX0/fLVNhGeHtd7uh@hloinOfw)
Suggestions welcome! :)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 15 bytes
```
n->2*n%(2^32-1)
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P185IK09VwyjO2EjXUPN/QVFmXolGmoaRpuZ/AA "Pari/GP – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 bytes
```
Ñ%3pH
```
Bitwise rotation, like most answers here.
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0SUzcEg&input=MTI)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 39 bytes
```
$_=sprintf'0b%b',$_;$_=oct$_.int s/10//
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3ra4oCgzryRN3SBJNUldRyXeGiiWn1yiEq8HFFYo1jc00Nf//9/8X35BSWZ@XvF/XV9TPQNDAyCdlJkOVPJftwAA "Perl 5 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 45 bytes
```
lambda i:int(f'{i:32b}'[1:]+f'{i:32b}'[:1],2)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZRvzPycxNyklUSHTKjOvRCNNvTrTytgoqVY92tAqVhuJa2UYq2Ok@b@gCKRMw9DGxthQU9tQRyELwdHU/A8A "Python 3 – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~45~~ 39 bytes
*-6 bytes thanx to ceilingcat*
```
auto h(unsigned x){return x%2<<31|x/2;}
```
[Try it online!](https://tio.run/##RY1dC4IwGEav2694UQYbGOmMPlD6Jd3INnVQrzI3GJi/fVlE3p3ncOCR47jvpIyx8W6AnnmcTIdaQeCz1c5bhEBFXZfFKxxEtcTUoHx4pWs5OWWGGyGp0q1BDU5PjgUOozXoWpZQD9TfMclC1q@eE7J6eDYGGScz2X37nFc/Kjb63P2XyLfmehHn8nRc9xLf "C++ (gcc) – Try It Online")
]