英文:
Extract from array to integer
问题
从C语言数组0x00, 0x50, 0x52, 0x45, 0x01中提取数字0145525000的方法是:
#include <stdio.h>
int main() {
uint8_t arr[] = {0x00, 0x50, 0x52, 0x45, 0x01};
uint32_t number = 0;
for (int i = 0; i < 5; i++) {
number = (number << 8) | arr[i];
}
printf("Number: %d\n", number);
return 0;
}
需要从数组的最后一个元素转换为一个无符号整数。
英文:
How to extract the number 0145525000 from the array 0x00, 0x50, 0x52, 0x45, 0x01 in C language?
#include <stdio.h>
int main()
{
uint8_t arr[] = {0x00, 0x50, 0x52, 0x45, 0x01};
uint32_t number = 0;
// Sorry i dont know how to solve this
printf("Number: %d\n", number);
return 0;
}
It is necessary to convert from the last element to zero into one unsigned integer?
答案1
得分: 1
十六进制常数 0145525000
更正确地写作 0x0145525000
,包含至少 9
个十六进制数字(如果忽略前导的 0
),这在 uint32_t
类型的对象中无法表示。变量 number
应声明为 uint64_t
类型。
现在你需要做的是编写一个循环,将数组 arr
中的十六进制值以与变量 number
相反的顺序存储。
这是你需要的。
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main( void )
{
uint8_t arr[] = { 0x00, 0x50, 0x52, 0x45, 0x01 };
const size_t N = sizeof( arr ) / sizeof( *arr );
uint64_t number = 0;
for (size_t i = N; i != 0; )
{
number = 0x100 * number + arr[--i];
}
printf( "%010" PRIx64 "\n", number );
}
程序输出为
0145525000
for 循环中的语句
number = 0x100 * number + arr[--i];
也可以重写为
number = ( number << 8 ) + arr[--i];
英文:
The hexadecimal constant 0145525000
that will be more correctly to write like 0x0145525000
contains at least 9
hexadecimal digits (if to ignore the leading 0
) that can not be represented in an object of the type uint32_t
. The variable number
should be declared as having type uint64_t
.
Now what you need is to write a loop that will store hexadecimal values present in the array arr
in the reverse order to the variable number
.
Here you are.
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main( void )
{
uint8_t arr[] = { 0x00, 0x50, 0x52, 0x45, 0x01 };
const size_t N = sizeof( arr ) / sizeof( *arr );
uint64_t number = 0;
for (size_t i = N; i != 0; )
{
number = 0x100 * number + arr[--i];
}
printf( "%010" PRIx64 "\n", number );
}
The program output is
0145525000
The statement within the for loop
number = 0x100 * number + arr[--i];
may be rewriten also like
number = ( number << 8 ) + arr[--i];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论