本文介绍了写“int”值到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有这个数组:

Hi,
I have this array :

`BYTE set[6] = { 0x15, 0x12, 0x84, 0x03, 0x00, 0x00 }`

我需要插入这个值:int Value = 900; ....最后4个字节。实际上从int转换为十六进制然后写入数组内...

这可能吗?



我已经有了BitConverter :: GetBytes功能,但这还不够:(



谢谢,

and i need to insert this value : int Value = 900; ....on last 4 bytes. Practically to convert from int to hex and then to write inside the array...
Is this possible ?

I already have "BitConverter::GetBytes" function, but that's not enough :(

Thank you,

推荐答案

int value = 900;
BYTE* pValue=(BYTE*)&value;
//pValue[0], pValue[1], pValue[2] & pValue[3] will contain the 4 bytes.





2)在循环中对int使用shift:



2) use shift on your int in a loop :

int value = 900;
int tmp=value;
for(int i=0;i<4;++i)
{
  initialized_byte_array[i]=(tmp& 0xFF);
  tmp=tmp>>8;
}



tmp var用于保持价值不变。



with


The tmp var is used to keep value intact.

with

#define BYTE unsigned char






or

#define BYTE char


int value=900;
stringstream stream;
stream.write( (char*)&value, sizeof( value ) );   ///Writing it once

BYTE bytes[4];
for ( int i = 0; i < 4; i++ )
{
   stream.read( &bytes[i], sizeof( BYTE ) );

} 



第二个解决方案是.....复制整个内存到字节数组




Second solution is ..... copy whole memory to the byte array

int value=900;
BYTE bytes[4];
memcpy( bytes, value, 4 );


typedef unsigned char BYTE;

BYTE set[6] = { 0x15, 0x12, 0x84, 0x03, 0x00, 0x00 };

int inValue = 900;

// Write
* ((int *) (set + (sizeof(set) - sizeof(int)))) = inValue;

// Read
int outValue = * ((int *) (set + (sizeof(set) - sizeof(int))));





回复其他问题:





In reply to additional question:

BYTE set[16]={0xC7,0x80,0xEA,0x04,0x00,0x00,0xB0,0x04,0x00,0x00,0x8B,0xE5,0x5D,0xC2,0x08,0x00 };

// Write
* ((int *) (set + 5)) = inValue;

// Read
int outValue = * ((int *) (set + 5));





阅读指针。此外,如果您在调试器中运行此代码,则可以验证它是否有效。



Read up on pointers. Also if you run this code in a debugger you can verify that it works.


这篇关于写“int”值到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:01