Skip to content

Instantly share code, notes, and snippets.

@rurumimic
Created September 15, 2018 04:32
Show Gist options
  • Save rurumimic/15f5e59e0ab05099b1cb19f8b3d4514c to your computer and use it in GitHub Desktop.
Save rurumimic/15f5e59e0ab05099b1cb19f8b3d4514c to your computer and use it in GitHub Desktop.
비트 놀이
import Foundation
let x = 20
print(x&(x-1)) // 오른쪽 비트 끄기
print(x|(x+1)) // 제일 오른쪽 0의 비트 켜기
print(x&(x+1)) // 뒤에 딸린 1들을 끄기
print(x|(x-1)) // 뒤에 딸린 0들을 켜기
print((~x)&(x+1)) // 제일 오른쪽 0만 켜고 다른 것 다 끄기
print((~x)|(x-1)) // 제일 오른쪽 1만 끄고 다른 것 다 켜기
print((~x)&(x-1)) // 뒤에 딸린 0들만 켜고 다른 것 다 끄기
print((~x)|(x+1)) // 뒤에 딸린 1들만 끄고 다른 것 다 켜기
print(x&(-x)) // 제일 오른쪽 1만 남기고 다 끄기
print(x^(x-1)) // 제일 오른쪽 비트 1과 후행비트 0들만 켜기
let y = 22
print(y^(y-1))
print(x^(x+1)) // 제일 오른쪽 비트 0과 후행비트 1들만 켜기
print( ((y&(-y))+y)&y ) // 제일 오른쪽 연속된 1들만 끄기
let z = 18
print( ((z&(-z))+z)&z ) // 제일 오른쪽 연속된 1들만 끄기
var topping = (1 << 20) - 1
print( topping ) // 20개의 모든 비트가 켜짐
topping |= (1 << 3) // 토핑 추가
print( topping )
func binString(_ num: Int) -> String {
var s = ""
var n = num
for _ in 1...64 {
s += ((n & 1 == 1) ? "1" : "0")
n >>= 1
}
return s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment