我正在嘗試從 Core Foundation CFDataRef 中獲取最左邊的 N 位。CF 和 C 的新手,所以這就是我到目前為止所得到的。它列印出 0,所以有些不對勁。
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;
}
感謝您的幫助!
uj5u.com熱心網友回復:
由于您只關心前四個位元組中的位,因此您可以將位元組復制到一個整數,然后對該整數執行位移。
#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;
}
您仍然可以在 CF 中執行 memcpy
uj5u.com熱心網友回復:
一般來說,要從 x 中獲取 n 個最左邊的位,您必須執行類似的操作
x >> ((sizeof(x) * 8) - n)(我假設位元組由 8 位組成)
我無權訪問蘋果的設備,也不知道它的 API,但很少評論:
- 您沒有
ret在您提供的代碼中定義。(而且我認為它不是由蘋果的庫定義的) - 我無法用我的搜索引擎找到 CFNumberGetInt32() 并且不知道它可以做什么。請發布具有足夠背景關系的可構建代碼以理解它
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488058.html
上一篇:將重復數字添加到二叉搜索樹
下一篇:二叉樹的分段錯誤
