Home > Net >  How to get the leftmost bits from Core Foundation CFDataRef?
How to get the leftmost bits from Core Foundation CFDataRef?

Time:06-09

I'm trying to get the N leftmost bits from a Core Foundation CFDataRef. New to CF and C, so here's what I've got so far. It's printing out 0, so something's off.

int get_N_leftmost_bits_from_data(int N)
{
    // Create a CFDataRef from a 12-byte buffer
    const unsigned char * _Nullable buffer = malloc(12);
    const CFDataRef data = CFDataCreate(buffer, 12);

    const unsigned char *_Nullable bytesPtr = CFDataGetBytePtr(data);

    // Create a buffer for the underlying bytes
    void *underlyingBytes = malloc(CFDataGetLength(data));

    // Copy the first 4 bytes to underlyingBytes
    memcpy(underlyingBytes, bytesPtr, 4);

    // Convert underlying bytes to an int
    int num = atoi(underlyingBytes);

    // Shift all the needed bits right
    const int numBitsInByte = 8;
    const int shiftedNum = num >> ((4 * numBitsInByte) - N);

    return shiftedNum;
}

Thank you for the help!

CodePudding user response:

Since you're only concerned about the bit in the first four bytes, then you could just copy the bytes over to an integer then perform a bit-shift on that integer.


#include <string.h>
#include <stdint.h>
int main(){
    
    uint8_t bytes[12] = {0};
    for(int n = 0; n < sizeof(bytes) ;   n){
        bytes[n] = n 0xF;
        //printf("x\n",bytes[n]);
    }
    uint32_t firstfour = 0;
    //copy the first four bytes
    memcpy(&firstfour,bytes,sizeof(uint32_t));
    //get the left most bit
    uint32_t bit = firstfour>>31&1;
    
    return 0;
}

You can still perform memcpy in CF

CodePudding user response:

In general, to get n leftmost bits from x, you have to do something like x >> ((sizeof(x) * 8) - n) (I assume that byte consists of 8 bits)

I don't have access to apple's device and don't know its API but few remarks:

  • You don't define ret in your's supplied code. (and I don't think it is defined by apple's library)
  • I was not able to find CFNumberGetInt32() with my search engine and have no clue what it could do. Please post buildable code with enough context to understand it
  • Related