C语言 C 以十六进制值初始化数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33454988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:11:52  来源:igfitidea点击:

C initialize array in hexadecimal values

carraysstringhexunsigned

提问by Kingamere

I would like to initialize a 16-byte array of hexadecimal values, particularly the 0x20 (space character) value.

我想初始化一个 16 字节的十六进制值数组,特别是 0x20(空格字符)值。

What is the correct way?

什么是正确的方法?

unsigned char a[16] = {0x20};

or

或者

unsigned char a[16] = {"0x20"};

Thanks

谢谢

采纳答案by Raghu Srikanth Reddy

There is a GNU extension called designated initializers. This is enabled by default with gcc

有一个 GNU 扩展称为指定初始化程序。默认情况下启用此功能gcc

With this you can initialize your array in the form

有了这个,你可以在表单中初始化你的数组

unsigned char a[16] = {[0 ... 15] = 0x20};

回答by Weather Vane

Defining this, for example

定义这个,例如

unsigned char a[16] = {0x20, 0x41, 0x42, };

will initialise the first three elements as shown, and the remaining elements to 0.

将如图所示初始化前三个元素,并将其余元素初始化为0.

Your second way

你的第二种方式

unsigned char a[16] = {"0x20"};

won't do what you want: it just defines a nul-terminated string with the four characters 0x20, the compiler won't treat it as a hexadecimal value.

不会做你想做的事:它只是用四个字符定义了一个以空字符结尾的字符串0x20,编译器不会把它当作一个十六进制值。

回答by user3386109

The first way is correct, but you need to repeat the 0x20,sixteen times. You can also do this:

第一种方法是正确的,但你需要重复0x20,十六次。你也可以这样做:

unsigned char a[16] = "                ";

回答by kcraigie

unsigned char a[16] = {0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20};

or

或者

unsigned char a[16] = "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20";

回答by Alex Lop.

I don't know if this is what you were looking for, but if the size of the given array is going to be changed (frequently or not), for easier maintenance you may consider the following method based on memset()

我不知道这是否是您要找的,但是如果给定数组的大小将要更改(经常或不),为了更容易维护,您可以考虑以下基于memset() 的方法

#include <string.h>

#define NUM_OF_CHARS 16

int main()
{
    unsigned char a[NUM_OF_CHARS];

    // initialization of the array a with 0x20 for any value of NUM_OF_CHARS
    memset(a, 0x20, sizeof(a));

    ....
}

回答by M3RS

I would use memset.

我会使用memset.

No need to type out anything and the size of the array is only provided once at initialisation.

无需输入任何内容,数组的大小仅在初始化时提供一次。

#include <string.h>

int main(void)
{
  unsigned char b[16];
  memset(b, 0x20, sizeof(b));
}