整数文字“255”时溢出存储到“INT8”

问题描述 投票:0回答:2

我有以下的代码,我碰到下面的错误。整数文字“255”时溢出存储到“INT8”

func decodeIDArrayItem(index:Int, tokenArray:UnsafeMutablePointer<CChar>){

    var value = tokenArray[index * 4] & 0xFF
    value <<= 8;
    value |= tokenArray [index * 4 + 1] & 0xFF
    value <<= 8;
    value |= tokenArray [index * 4 + 2] & 0xFF
    value <<= 8;
    value |= tokenArray [index * 4 + 3] & 0xFF

}

有什么想法吗?

ios xcode swift3
2个回答
0
投票
func decodeIDArrayItem(index:Int, tokenArray:UnsafeMutablePointer<CChar>) -> UInt32{

    var value:UInt32 = UInt32(tokenArray[index * 4]) & 0xFF

    value <<= 8
    value |= UInt32(tokenArray [index * 4 + 1]) & 0xFF
    value <<= 8
    value |= UInt32(tokenArray [index * 4 + 2]) & 0xFF
    value <<= 8
    value |= UInt32(tokenArray [index * 4 + 3]) & 0xFF


    return value

}

0
投票

我希望你试图提取8位数据转换成32位格式。你得到的问题,因为符号字符。任何尝试用UInt32的,它会正常工作。我希望下面的代码会帮助你。

func decodeIDArrayItem(index:Int, tokenArray:UnsafeMutablePointer<CChar>) -> UInt32{

    // convert into 4 byte
    // tokenArray[index * 4] of type UInt8 formate
    var value:UInt32
    let byte1 : UInt32 = UInt32(tokenArray[index * 4]) // 0 index
    let byte2 : UInt32 = UInt32(tokenArray[index * 4 + 1])<<8 // 1 index
    let byte3 : UInt32 = UInt32(tokenArray[index * 4 + 2])<<16 // 2 index
    let byte4 : UInt32 = UInt32(tokenArray[index * 4 + 2])<<32 // 3 index

    value = byte1 | byte2 | byte3 | byte4

     return value



}
© www.soinside.com 2019 - 2024. All rights reserved.