Weird results converting data bits to UInt16

I can't for the life of me understand why I am getting the output I get from this function, in the swift CLI (swift-driver version: 1.26.9 Apple Swift version 5.5 (swiftlang-1300.0.31.1 clang-1300.0.29.1))

import SwiftUI

func stringToColor(_ string: String) -> Color {
    let bits: Data = {
        var safeString: String
        if string == "" { safeString = "__"}
        if string.count == 1 { safeString = string + "_" }
        else { safeString = String(string.prefix(2)) }
        return safeString.data(using: .utf8) ?? Data([0x32,0x32])
    }()
    
    let number = UInt16(bits[0] << 8 + bits[1])
    print(bits[0], bits[1])
    print("Number and type: ", number, type(of:number))
    return .blue
}
stringToColor("hi")
104 105
Number and type:  105 UInt16
$R4: Color = {
  provider = {}
}

Outside of that function, I get sane output:

 1> let bits = [104,105]
bits: [Int] = 2 values {
  [0] = 104
  [1] = 105
}
  2> let number = UInt16(bits[0] << 8 + bits[1])
number: UInt16 = 26729

Anyone have insight?

Since Data uses UInt8, bits[0] << 8 becomes 0.

3 Likes

D'oh! Yep. That's the problem. Thanks!

1 Like
Terms of Service

Privacy Policy

Cookie Policy