简体   繁体   English

c如何使用memcpy将十六进制值复制到数组中

[英]c how to copy hexadecimal value into array using memcpy

I am working with C , and I have a uint8_t array of hex values and I want to add another value to it via memcpy dynamically eg 我正在使用C ,并且我有一个uint8_t array hexuint8_t array ,我想通过memcpy动态地向它添加另一个值,例如

I have an array: uint8_t sample['0x23', '0x34',...] etc ...and I want to copy another Hex character into the array later on. 我有一个数组: uint8_t sample['0x23', '0x34',...]等...,我想uint8_t sample['0x23', '0x34',...]另一个Hex character复制到array中。 How is this done? 怎么做? If this question has been answered before, sorry, I couldn't find it. 如果以前已经回答过此问题,对不起,我找不到。 I am new to C , and these pointers are giving me hell. 我是C新手,而这些pointers使我下地狱。 Thanks in advance. 提前致谢。

You could write simply 你可以简单地写

sample[4] = '\x0A';

If you want to use memcpy then the valid code will look like 如果要使用memcpy,则有效代码如下所示

memcpy( &sample[4], "\x0A", 1 );

or 要么

memcpy( sample + 4, "\x0A", 1 );

That is you need to use string literal instead of character constant. 那就是您需要使用字符串文字而不是字符常量。

I wonder if what is really being asked is how to add a new value to the end of the array. 我想知道是否真正要问的是如何在数组末尾添加新值。

In C, there is no "array" class, so you must either manage the memory and associated pointers yourself, or use a pre-defined function library that does it all for you. 在C语言中,没有“数组”类,因此您必须自己管理内存和关联的指针,或者使用预定义的函数库为您完成所有这些工作。 Let's assume the former ie the programmer is doing the management themselves. 让我们假设前者,即程序员自己进行管理。

Before you can assign or copy a new value into your array, you'll need to ensure there is enough space. 在将新值分配或复制到数组中之前,需要确保有足够的空间。 One way to manage this follows: 解决此问题的一种方法如下:

int     array_size = 10;
uint8_t sample[array_size];
uint8_t i = 4;    /* assuming array index cannot exceed 255 */

if (i < array_size) {
    sample[i] = 0x0a;
}

The key here is that your sample array occupies just 10 bytes of memory and you need to make sure that your accesses to the sample array do not fall outside that bound. 这里的关键是示例数组仅占用10个字节的内存,并且需要确保对示例数组的访问不超出该范围。

If indeed the desire is to append a value to the end of the array, then another variable will have to be added to keep track of the last insertion point/index and use that for i in the example. 如果确实希望将一个值附加到数组的末尾,则必须添加另一个变量来跟踪最后的插入点/索引,并在示例中将其用于i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM