C语言 将int转换为C中的字节数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3447735/
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 06:07:27  来源:igfitidea点击:

Convert int to array of bytes in C?

c

提问by Emi

I need to convert decimal number stored in an int, to a array of bytes (aka stored in a unsigned char array).

我需要将存储在 int 中的十进制数转换为字节数组(也就是存储在 unsigned char 数组中)。

Any clues?

有什么线索吗?

回答by leppie

Or if you know what you are doing:

或者,如果您知道自己在做什么:

int n = 12345;
char* a = (char*)&n;

回答by Emi

Simplest possible approach - use sprintf (or snprintf, if you have it):

最简单的方法 - 使用 sprintf(或 snprintf,如果有的话):

unsigned char a[SOMESIZE]
int n = 1234;
sprintf( a, "%d", n );

Or if you want it stored in binary:

或者,如果您希望它以二进制形式存储:

unsigned char a[sizeof( int ) ];
int n = 1234;
memcpy( a, & n, sizeof( int ) );

回答by Hernán Eche

This could work

这可以工作

int n=1234;    
const int arrayLength=sizeof(int);
unsigned char *bytePtr=(unsigned char*)&n;

for(int i=0;i<arrayLength;i++)
{
   printf("[%X]",bytePtr[i]);
}

Take care of order that depends on endianness

处理依赖于字节序的顺序

回答by Zarel

Warning: untested code.

警告:未经测试的代码。

This should be an endianness-agnostic conversion. It goes from low to high. There's probably a more efficient way to do it, but I can't think of it at the moment.

这应该是与字节序无关的转换。它从低到高。可能有一种更有效的方法来做到这一点,但我目前想不出。

#include <limits.h> // CHAR_BIT, UCHAR_MAX

int num = 68465; // insert number here
unsigned char bytes[sizeof(int)];
for (int i=0; i<sizeof(int); i++)
{
    bytes[i] = num & UCHAR_MAX;
    num >>= CHAR_BIT;
}

I'm posting this mostly because I don't see another solution here for which the results don't change depending on what endianness your processor is.

我发布这个主要是因为我在这里没有看到另一个解决方案,其结果不会根据您的处理器的字节顺序而改变。

回答by kriss

I understand the problem as converting a number to a string representation (as Neil does).

我将问题理解为将数字转换为字符串表示形式(如 Neil 所做的那样)。

Below is a simple way to do it without using any lib.

下面是一种不使用任何库的简单方法。

int i = 0;
int j = 0;
do {a[i++] = '0'+n%10; n/=10;} while (n);
a[i--] = 0;
for (j<i; j++,i--) {int tmp = a[i]; a[i] = a[j]; a[j] = tmp;}

The question probably needs some clarification as others obviously understood you wanted the underlying bytes used in internal representation of int (but if you want to do that kind of thing, you'd better use some fixed size type defined in instead of an int, or you won't know for sure the length of your byte array).

这个问题可能需要一些澄清,因为其他人显然理解你想要在 int 的内部表示中使用的底层字节(但如果你想做那种事情,你最好使用一些固定大小的类型而不是 int,或者你不会确定你的字节数组的长度)。