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!
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("%02x\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