从数组提取为整数

huangapple go评论82阅读模式
英文:

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 &lt;stdio.h&gt;

int main()
   {
    uint8_t arr[] = {0x00, 0x50, 0x52, 0x45, 0x01};
    uint32_t number = 0;

    // Sorry i dont know how to solve this

    printf(&quot;Number: %d\n&quot;, 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 &lt;stdio.h&gt;
#include &lt;stdint.h&gt;
#include &lt;inttypes.h&gt;

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( &quot;%010&quot; PRIx64 &quot;\n&quot;, number );
}

The program output is

0145525000

The statement within the for loop

number = 0x100 * number + arr[--i];

may be rewriten also like

number = ( number &lt;&lt; 8 ) + arr[--i];

huangapple
  • 本文由 发表于 2023年7月3日 19:53:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定