0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift】カラーコードを16進数変換してIntにする

Posted at

実行環境

  • Paiza.io

コード

import Foundation

let hex = "FFFFFF"

if let hexNumber = Int(hex, radix: 16) {
    let red = (hexNumber >> 16) & 0xFF
    let green = (hexNumber >> 8) & 0xFF
    let blue = hexNumber & 0xFF
    print("\(red),\(green),\(blue)")
}
出力.
255,255,255

雑記

  • Intを初期化する際に第一引数にhex, 第二引数にradixをセットすることができる。radixの中で2進数だったり16進数を指定できる。
  • そのあとの{}の中でビットシフトとAND演算を使うことでIntに変換することが可能。
  • redは16bit右にずらしてhexNumberの左2桁を、greenは8bit右にずらして真ん中2桁を、blueは最後の2桁を取得することが可能。
  • 最後に& 0xFFをすることで、右の8bitの情報を取得することができる。

  • 漠然としか理解できていないので、この辺りの情報は基本情報あたりを勉強しておくのが良いと思いました
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?