Bit shift in fast overall function

I am trying to write a generic function that requires bit shifting operations. I get behavior that I don't understand. Here is a simple function that demonstrates the problem.

func testBytes<T: IntegerType>(bytesIn: [UInt8], inout dataOut: T){ let outputSize = sizeof(T) var temp: T = 0 dataOut = 0 temp = bytesIn[0] as T temp = temp << 1 } 

If I do this, the last line will give me an error in xcode "T does not convert to Int".

I can change the last line to temp = temp << (1 as T)

And then the error for this line will change to "T does not convert to UInt8"

None of these error messages make sense to me in this context. Is there something I can do to enable bit offsets on a generic type?

+5
source share
1 answer

I have a blog entry in this section that goes in more detail, but essentially there are three steps:

  • Create a new protocol with bit shift operators and constructor from UInt8 :

     protocol BitshiftOperationsType { func <<(lhs: Self, rhs: Self) -> Self func >>(lhs: Self, rhs: Self) -> Self init(_ val: UInt8) } 
  • Declaring an extension for each of the integer types is easy because they already implement everything in BitshiftOperationsType :

     extension Int : BitshiftOperationsType {} extension Int8 : BitshiftOperationsType {} extension Int16 : BitshiftOperationsType {} extension Int32 : BitshiftOperationsType {} extension Int64 : BitshiftOperationsType {} extension UInt : BitshiftOperationsType {} extension UInt8 : BitshiftOperationsType {} extension UInt16 : BitshiftOperationsType {} extension UInt32 : BitshiftOperationsType {} extension UInt64 : BitshiftOperationsType {} 
  • Add a general constraint, so T matches your new protocol:

     func testBytes<T: IntegerType where T: BitshiftOperationsType>(bytesIn: [UInt8], inout dataOut: T){ let outputSize = sizeof(T) var temp: T = 0 dataOut = 0 temp = T(bytesIn[0]) temp = temp << 1 } 

Thanks to Martin R. for the correction for the rough bit that I had here before!

+7
source

Source: https://habr.com/ru/post/1206092/


All Articles