Brian Ogden Brian Ogden - 5 months ago 25
Swift Question

Issues bit shifting UInt8 after converting to from Objective C to Swift

I am streaming video to a UIImage in my app using

NSURLConnection
. Part of my code, that works in Objective C I am having trouble converting to Swift:

func connection(connection: NSURLConnection, didReceiveData data: NSData) {

//...other code

UInt32 sizeOfJPEG_1; //same type as was in Objective C

var payloadsize = [UInt8](count: 4, repeatedValue: 0x00) //was uint8_t in Objective C
data.getBytes(&payloadsize[1], range: NSMakeRange(12, 3))
payloadsize[0] = 0
sizeOfJPEG_1 = (payloadsize[1] << 16) + (payloadsize[2] << 8) + payloadsize[3]//here is the problem
//UInt32(sizeOfJPEG_1 = (payloadsize[1] << 16) + (payloadsize[2] << 8) + payloadsize[3]) //the way I am currently dealing with converting my shifting and additions to the correct sizeOfJPEG_1 UInt32 argument type
//..more code
}


I am having two issues here:


  1. I am not sure of the best way to convert the payloadsize UInt8 bitshifting and additions to the argument UInt32
    enter image description here

  2. More importantly, possibly, to figure out first, is the runtime error I get shifting a UInt8 << 16, in objective C the type was uint8_t, I do not know if that was a legal operation in Objective C with a tyupe of uint8_t and just is not in Swift with a type of UInt8



I am getting an overflow error because I am left shifting a UInt8 << 16 as well as UInt8 << 8:
fatal error: shift amount is larger than type size in bits

enter image description here

I think I understand Objective C will quietly shift a uint8_t << 16 without crashing but I do not know how to calculate this, what is the result of uint8_t << 16, wouldn't it be 0? (uint8_t is defined as unsigned char)

Answer

Unlike (Objective-)C, Swift does not promote smaller integer types to int or unsigned int, so you have to do that explicitly (before shifting the data):

let sizeOfJPEG_1 = UInt32(payloadsize[1]) << 16 + UInt32(payloadsize[2]) << 8 + UInt32(payloadsize[3])