1

What is the Swift 2+ equivalent for this line of code found in this answer?.

 let a:UInt16 = UInt16(bytes[0]) * 256 + UInt16(bytes[1])  
Community
  • 1
  • 1
WaterNotWords
  • 997
  • 1
  • 9
  • 24

1 Answers1

3

by checking that link .. first you have to define bytes array like [UInt8]

   let bytes:[UInt8] = [0x01, 0x02]
   let a = UInt16(bytes[0]) * 256 + UInt16(bytes[1])
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
  • Haha.. Thanks. Not a special initializer at all! – WaterNotWords Mar 04 '16 at 04:43
  • Good answer, but shifting by 8 makes it easier to understand than multiplying by 256 – Kevin Mar 04 '16 at 04:45
  • @Kevin yes... but OP wants equivalent code .. which doesn't need at all... actually he doesn't initialise bytes array ... thats mistacke – Bhavin Bhadani Mar 04 '16 at 04:46
  • @Kevin I think what you told you is this `let a = (UInt16(bytes[1]) << 8) + UInt16(bytes[0])` right – Bhavin Bhadani Mar 04 '16 at 04:48
  • Shifting by 8 is exactly the same as multiplying by 256 (2^8), shifting is generally used when you're packing bits together. – Kevin Mar 04 '16 at 04:49
  • @Kevin that answer is fine too.. but I just confused the bytes variable with some sort of initializer that took the early swift (pre 1.2 I think) Byte type, since the question was old and I didn't read it fully nor notice the lower case 'b'. Not enough sleep, probably. Either way the answer is obvious, I think. Thanks guys. – WaterNotWords Mar 04 '16 at 08:49