[英]How can I access the bytes form an integer
我正在嘗試在.bmp
文件中的像素的字節(或八位字節)和隨機生成的整數(不包括最重要的整數)中的 3 個字節之間進行異或。 我有點理解最重要的字節取決於字節序,通常它是句子中傳輸的第一個字節。 在pix
數組中,我存儲了每個像素的每個八位字節。 w
和h
都等於800
並且是.bmp
圖片(800 x 800)的尺寸, R
是隨機數數組。
我嘗試執行以下操作,但在一些增量后它會給我一個分段錯誤。
unsigned char *pix = malloc((3 * w * h) * sizeof(unsigned char));
for(int i = 0; i < (3 * w * h); i++)
fread(&pix[i], sizeof(char), 1, fin);
uint32_t *R = malloc((3 * ((2 * w * h) - 1)) * sizeof(uint32_t));
unsigned char bytes[4];
for(k = 0; k < (3 * w * h); k = k + 3)
{
bytes[0] = (R[3 * w * h + k] >> 24) & 0xFF;
bytes[1] = (R[3 * w * h + k] >> 16) & 0xFF;
bytes[2] = (R[3 * w * h + k] >> 8) & 0xFF;
bytes[3] = R[3 * w * h + k] & 0xFF;
ch[k] = bytes[1] ^ pix[k];
ch[k + 1] = bytes[2] ^ pix[k + 1];
ch[k + 2] = bytes[3] ^ pix[k + 2]
}
typedef enum
{
LITTLE = 0xff000000,
BIG = 0x000000ff,
}ENDIANESS;
static ENDIANESS endianess;
ENDIANESS DetectEndianess(void)
{
union
{
uint8_t u8[sizeof(unsigned int)];
unsigned int u;
}udata = {.u = 0xff};
return (endianess = (udata.u8[0] == 0xff ? LITTLE : BIG));
}
static inline ENDIANESS GetEndianess(void)
{
return endianess;
}
uint32_t GetUint32FromRGB(uint8_t *ptr)
{
union u32u
{
uint8_t u8[4];
uint32_t u32;
}union32 = (GetEndianess() == LITTLE ? (union u32u){.u8[0] = *ptr, .u8[1] = *(ptr + 1), .u8[2] = *(ptr + 2)} : (union u32u){.u8[2] = *ptr, .u8[1] = *(ptr + 1), .u8[0] = *(ptr + 2)});
return union32.u32 & GetEndianess();
}
uint32_t Xor3LowerBytes(uint32_t a, uint32_t b)
{
return (a & GetEndianess()) ^ (b & GetEndianess());
}
或者,如果您不關心字節順序(在此示例中為 LITTLE)
uint32_t Xor3lowerBytes(void *ptr, uint32_t value)
{
uint32_t *u32 = ptr;
return (*u32 & 0xff000000) ^ value;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.