[英]How to store odd and even position bits to another pointer using C?
我有两个指针。 一个是输入ptr,另一个是输出。
我的输入指针包含二进制值
15.................0
0011 0110 1111 0111 - unsigned 16 bit
1011 0100 1011 1100 - unsigned 16 bit
首先,我想从两行中获取偶数位,并且必须将其填充到输出指针中。
o/p 指针将是
0110 0110 0110 1111 (even position bits from both)..from right to left and assume 0 to 15.
1100 1110 0101 1101 (odd position bits from both)
如何通过使用指针来做到这一点? 我对指针很陌生
转换您的代码以使用指针通常非常简单。
举个例子:
uint16_t compute(uint16_t a, uint16_t b)
{
return ((a | b) & MY_BIT_MASK) >> (a & 2); // some arbitrary operations
}
uint16_t compute_p(uint16_t *a, uint16_t *b)
{
return ((*a | *b) & MY_BIT_MASK) >> (*a & 2); // some arbitrary operations via pointers
}
如果您向我们展示您的实际代码,我们或许可以为您提供更多帮助。 但基本上,当你有一个指向 uint16_t 的指针时,你可以通过两种方式使用它:
uint16_t *p;
p <- to mean the pointers value, which is an address, you assign it to other pointers, or increment it, so it would point to the next uint16_t in memory
*p <- to use it in expressions on place of a uint16_t, this way your code will each time fetch the actual 16 bit value pointed to by p
p[i] <- with int i, This is basically a synonym to *(p+i) as long as i is non-negative
*(p + i) <- with int i, This is also the value of 16 bit integer where p points to, or the next, or previous etc 16 bit value. In this form, negative i can be used as well
p - q <- with uint16* q the difference of the pointers, in case of uint16_t * types, this basically means "how many 16 but ints I can store and addresses q, q+1, q+2, q+3 .... p-1", assuming p>q
据我所知,你不能用 C 中的指针做你想做的事。这是因为,据我所知,你不能在 C 中创建指向位的指针,它们只能指向字节。
我能想到的一种解决方案是使用位掩码。 通过屏蔽单个位,将它们移动到您想要的位置,并将它们分配到一个新的空白变量中,可以实现您想要的。 在这里,检查以下内容:
#define bitmask(_x_) (1 << (_x_))
#include <stdio.h>
#include <inttypes.h>
int main( ){
uint16_t in1 = 14071; // 0011 0110 1111 0111
uint16_t in2 = 46268; // 1011 0100 1011 1100
uint16_t out1 = 0;
uint16_t out2 = 0;
for ( int i = 0; i < 8; i++ ) {
out1 |= ( in1 & bitmask( i * 2 ) ) >> i;
out1 |= ( ( in2 & bitmask( i * 2 ) ) >> i ) << 8;
out2 |= ( in1 & bitmask( i * 2 + 1 ) ) >> ( i + 1 );
out2 |= ( ( in2 & bitmask( i * 2 + 1 ) ) >> ( i + 1 ) ) << 8;
}
printf( "out1: %u\nout2: %u", out1, out2 );
return 0;
}
输出是:
out1: 26223
out2: 52829
其中具有您想要的基数 2 的形式。
编辑:具有相同输出的替代版本,这可能对读者更友好,我不知道性能方面:
#define bitMASK(maskee,bit) (((maskee) >> (bit)) & 1)
#include <stdio.h>
#include <inttypes.h>
int main( ){
uint16_t in1 = 14071; // 0011 0110 1111 0111
uint16_t in2 = 46268; // 1011 0100 1011 1100
uint16_t out1 = 0;
uint16_t out2 = 0;
for ( int i = 0; i < 8; i++ ) {
out1 |= bitMASK( in1, 2 * i ) << i;
out1 |= bitMASK( in2, 2 * i ) << ( 8 + i );
out2 |= bitMASK( in1, 2 * i + 1 ) << i;
out2 |= bitMASK( in2, 2 * i + 1 ) << ( 8 + i );
}
printf( "out1: %u\nout2: %u", out1, out2 );
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.