Is there a JavaScript function the same as CFSwapInt16LittleToHost

Viewed 14

I am trying to convert some code from Xcode into React Native.

I have come accross this code:

    else if([characteristic.UUID isEqual:self.respCharUUID]) {
    uint16_t rpm = 0;
    
    if ((reportData[0] & 0x01) == 0) {
        rpm = reportData[1];
    }
    else {
        rpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));
    }

However, I do not understand what CFSwapInt16LittleToHost does except in the docs that say:

The integer with its bytes swapped. If the host is little-endian, this function returns arg unchanged.

located here from apple documentation.

Is there a Javascript function that is the same? If so, how would i use it?

Cheers in advance.

1 Answers

Your Swift code is checking whether the number (as bytes) is big- or little-endian, and swapping little to big (if that is what the host requires). Here's an example of how to swap big/little in JS:

How do I swap endian-ness (byte order) of a variable in javascript

iOS is more commonly little-endian but is not guaranteed as such:

Is iOS guaranteed to be little-endian?

However, Apple provide a function to return the endianness of the host. You may have to write a wrapper for this in React Native.

https://developer.apple.com/documentation/corefoundation/1425298-cfbyteordergetcurrent

Android is mostly guaranteed to be little-endian (but it wouldn't hurt to check):

Endianness of Android NDK

You can use the following Android function to check (again, you will probably have to write a wrapper for this):

https://developer.android.com/reference/java/nio/ByteOrder#nativeOrder()

Related