[英]How do I get 16 bit sections of a 64 bit unsigned long using an integer index?
I'm trying to return certain 16-bit sections from a 64-bit unsigned long and I'm stuck on how to accomplish this.我正在尝试从 64 位无符号长返回某些 16 位部分,但我一直坚持如何完成此操作。 Here is the function I am trying to implement:这是我正在尝试实现的 function:
// assume i is a valid index (0-3 inclusive)
unsigned short get(unsigned long* ex, int i) {
// return the 16-bit section based on the index i
}
For example, if I have unsigned long ex = 0xFEDCBA9876543210;
例如,如果我有unsigned long ex = 0xFEDCBA9876543210;
, then my function get(ex, 0)
would return 0x3210
, get(ex, 1)
would return 0x7654
, etc. I'm very new to C and I'm still trying to wrap my head around bit management and pointers. ,然后我的 function get(ex, 0)
将返回0x3210
, get(ex, 1)
将返回0x7654
,等等。我对 C 很陌生,我仍在尝试围绕位管理和指针。 Any advice or feedback is appreciated in helping me understand C better.任何建议或反馈都可以帮助我更好地理解 C。
You'll have to use a bit shift你必须使用位移位
#include <stdint.h>
uint16_t get(uint64_t ex, int i)
{
return (uint16_t)(ex >> i*16);
}
You can just pass by value.您可以按值传递。 There's no reason to pass a pointer.没有理由传递指针。 This will shift the bits to the right, meaning they become the low order value.这会将位向右移动,这意味着它们成为低阶值。 When it gets converted to a 16 bit type, it loses the higher order bits.当它转换为 16 位类型时,它会丢失高阶位。
I've included stdint.h
because it defines types of exact size.我已经包含了stdint.h
因为它定义了精确大小的类型。
I would use a mask along with bit shifting我会使用掩码和位移
unsigned short get(int index, unsigned long n)
{
if (index > 3 || index < 0)
return 0xFFFF; // well you have to see if you have control over the inputs.
return (n >> (index << 4)) & 0xFFFF; // will extract 2 bytes.
}
The way closest to what you're asking for is a union:最接近您要求的方式是工会:
#include <stdio.h>
#include <stdint.h>
int main(const int argc, const char * const argv[]) {
union {
uint64_t i;
uint16_t ia[4];
} u;
u.i = 0xFEDCBA9876543210;
printf("u.ia[0] %x\n", u.ia[0]);
}
Output is: Output 是:
u.ia[0] 3210
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.