数据转换
C语言:有一个数组B={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};转化为b=0xfedcba9876543210 #include <stdio.h>unsigned long hex(int data[]) {
unsigned long res = 0;
for(int i = 0; i < 16; ++i) {
res |= (unsigned long)(data & 0x0f) << (i * 4);
}
return res;
}
int main(void) {
int data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
printf("0x%lx\n", hex(data));
return 0;
}
#include <stdio.h>
int main()
{
long B={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//转化为b=0xfedcba9876543210;
long b=0;
for (int i=0;i<16;i++)
b+=(B<<(4*i));
printf("b=0x%lx\n", b);
return 0;
} sunrise085 发表于 2020-4-29 17:39
输出结果b=0x7530eca8 人造人 发表于 2020-4-29 17:33
输出结果b=0xfedcba98 zhuby 发表于 2020-4-29 17:49
输出结果b=0xfedcba98
试试这个
#include <stdio.h>
#include <stdint.h>
uint64_t hex(int data[]) {
uint64_t res = 0;
for(int i = 0; i < 16; ++i) {
res |= (uint64_t)(data & 0x0f) << (i * 4);
}
return res;
}
int main(void) {
int data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
printf("0x%lx\n", hex(data));
return 0;
}
人造人 发表于 2020-4-29 18:05
试试这个
0x76543210 zhuby 发表于 2020-4-29 18:08
0x76543210
再来
#include <stdio.h>
#include <stdint.h>
uint64_t hex(int data[]) {
uint64_t res = 0;
for(int i = 0; i < 16; ++i) {
res |= (uint64_t)(data & 0x0f) << (i * 4);
}
return res;
}
int main(void) {
int data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
printf("0x%llx\n", hex(data));
return 0;
}
人造人 发表于 2020-4-29 18:10
再来
这次OK了,谢谢大佬 zhuby 发表于 2020-4-29 17:46
输出结果b=0x7530eca8
可能是因为你的是32位系统吧。
试一下这个。long long 肯定是64位
#include <stdio.h>
int main()
{
long long B={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//转化为b=0xfedcba9876543210;
long long b=0;
for (int i=0;i<16;i++)
b+=(B<<(4*i));
printf("b=0x%llx\n", b);
return 0;
}
页:
[1]