Search code examples
c#swiftxamarin.iosbytebeacon

What is the equivalent of this swift Uint8 conversion in c#?


i'm trying to convert this swift snippet in c#, but i'm a bit confused. Basically, i need this function to get the Ranging Data from beacons, as is indicated here: https://github.com/google/eddystone/tree/master/eddystone-uid

func getTxPower( frameData: NSData) -> Int
{
let count = frameData.length
var frameBytes = [UInt8](repeating: 0, count: count)
frameData.getBytes(&frameBytes, length: count)
let txPower = Int(Int8(bitPattern:frameBytes[1]))
return txPower
}

I get a NSData and i convert it into a UInt8 array. I just need to get the element in second position and convert it into a signed int.

This is the c# code i tried:

int getTxPower(NSData frameData)
{
var count = frameData.Length;

byte[] frameBytes = new byte[Convert.ToInt32(count)];

Marshal.Copy(frameData.Bytes, frameBytes,0,Convert.ToInt32(count));

int txPower = frameBytes[1];

return txPower;
}

I expected to get negative value too, because, as written in the link, the TxPower has a value range from -100 dBm to +20 dBm at a resolution of 1 dBm.

Thanks to those who will help me.


Solution

  • Presumably instead of:

    int txPower = frameBytes[1];
    

    (which just extends an unsigned byte to 32 bits)

    int txPower = (int)((sbyte)frameBytes[1]);
    

    (which reinterpets the unsigned byte as a signed byte, then extends to 32 bits)

    Note that the (int) can be done implicitly, if it is clearer:

    int txPower = (sbyte)frameBytes[1];