Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a specific bit from an Integer in Swift?

Trying to convert my app to Swift from C++

C++:

static QWORD load64(const OCTET *x)
{
char i;
QWORD u=0;
    for(i=7; i>=0; --i) {
        u <<= 8;
        u |= x[i];
    }
    return u;
}

Swift:

func load64(x: UInt8) -> UInt64 {
    var u: UInt64 = 0;
    for var i=7; i>=0; --i {
        u <<= 8;
        u |= x[i];
    }
    return u;
}

But this line doesnt work in Swift:

u |= x[i];

And I can't seem to find any reference to selecting a specific bit from an integer... anyone know how?

like image 847
Wyllow Wulf Avatar asked Jan 31 '26 07:01

Wyllow Wulf


1 Answers

It is possible to use the |= operator in Swift, and it works the same as in C/C++.

The problem is that load64() in the C++ code essentially takes an array of OCTETs as an argument and accesses the array using a subscript. The Swift version takes a UInt8 as an argument, and you can't subscript an integer in Swift, just as you can't do that in C or C++.

As far as I can tell, the point of the C++ code is to build a 64-bit unsigned int from an array of 8 bytes provided in the array passed in as an argument. To get this to work in Swift, load64() will need to take an array of bytes as an argument, not just a single byte.

As an aside, if you have a large code base in C++ or C that you want to use in Swift, you don't have to re-write it in Swift. You may be able to write a C/C++ wrapper with a simplified interface and invoke it from Swift. I have a basic proof-of-concept tutorial on how to do that here: http://www.swiftprogrammer.info/swift_call_cpp.html

BTW, here is a Swift version of load64(), worked for me:

func load64(x: [UInt8]) -> UInt64 {
    var u: UInt64 = 0;
    for var i=7; i>=0; --i {
        u <<= 8;
        u |= UInt64(x[i]);
    }
    return u;
} 
like image 97
Anatoli P Avatar answered Feb 02 '26 23:02

Anatoli P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!