I would be surprised if CoPilot can reason numerically like this (understand "seventeenth bit" and "sixth bit" and generate the right code for that combination).
For python it seems to generate a more reasonable result at least:
# Swap the sixth bit and seventeenth bit of a 32-bit signed integer.
def swap_bits(x):
# Get the bit at position 6 and 17.
bit6 = x & (1 << 6)
bit17 = x & (1 << 17)
# Swap the bits.
x = x ^ (bit6 << 17)
x = x ^ (bit17 << 6)
return x
The function doesn't do the comment says it does.
The code to "Swap the bits." just turns the bits on.
>>> def swap_bits(x):
# Get the bit at position 6 and 17.
bit6 = x & (1 << 6)
bit17 = x & (1 << 17)
# Swap the bits.
x = x ^ (bit6 << 17)
x = x ^ (bit17 << 6)
return x
>>> x6 = (1 << 6)
>>> f"{x6:b}"
'1000000'
>>> s6 = swap_bits(x6)
>>> f"{s6:b}"
'100000000000000001000000'
Here's one that correctly swap bits. It could be made more concise.
>>> def swap_specific(x,i,j):
def get(x,p): return 1 if x & (1 << p) else 0
def set(x,p): return x ^ (1 << p)
def clr(x,p): return x & ~(1 << p)
bi, bj = get(x,i), get(x,j)
x = set(x,j) if bi else clr(x,j)
x = set(x,i) if bj else clr(x,i)
return x
>>> f"{x6:b}"
'1000000'
>>> b6 = swap_specific(x6,6,17)
>>> f"{b6:b}"
'100000000000000000'
I guess CoPilot has seen bit swapping in its Python training input but not in its Go training input.
The Python code is wrong because the 17th bit is shifted up, not down. Also, the bits are shifted by the wrong amount, not up/down by 11 (= 17 minus 6), but up by 6 and up by 17. What a joke.
Not only that, even if the shifts were correct, it's simply xoring the bits. The swap is completely wrong.
Yeah, it seems to be pretty heavily trained on Python. It's honestly still (and should be used as) a glorified autocomplete, which is pretty useful from time to time.
With just that prompt, Copilot keeps writing a comment about the function but never actually writes the function. Prompting to actually write the function by starting it with `func` gives:
// A Go function to swap the sixth bit and seventeenth bit of a 32-bit signed integer.
func swapBits(x int32) int32 {
return ((x & 0x0F) << 28) | ((x & 0xF0000000) >> 28)
}
And there you have it, the difference between real intelligence and regurgitation.
This is the kind of numerically specific coding that could be the basis of a CAPTCHA that CoPilot can't solve. Sixth bit, sixth byte, seventeenth bit, seventeenth byte, etc.