C++ int 到字节数组

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

C++ int to byte array

c++arraysbyteint

提问by justme_

I have this method in my java code which returns byte array for given int:

我的java代码中有这个方法,它返回给定int的字节数组:

private static byte[] intToBytes(int paramInt)
{
     byte[] arrayOfByte = new byte[4];
     ByteBuffer localByteBuffer = ByteBuffer.allocate(4);
     localByteBuffer.putInt(paramInt);
     for (int i = 0; i < 4; i++)
         arrayOfByte[(3 - i)] = localByteBuffer.array()[i];
     return arrayOfByte;
}

Can someone give me tip how can i convert that method to C++?

有人可以给我提示如何将该方法转换为 C++?

采纳答案by Donotalo

Using std::vector<unsigned char>:

使用std::vector<unsigned char>

#include <vector>
using namespace std;

vector<unsigned char> intToBytes(int paramInt)
{
     vector<unsigned char> arrayOfByte(4);
     for (int i = 0; i < 4; i++)
         arrayOfByte[3 - i] = (paramInt >> (i * 8));
     return arrayOfByte;
}

回答by James McNellis

You don't need a whole function for this; a simple cast will suffice:

你不需要一个完整的函数;一个简单的演员就足够了:

int x;
static_cast<char*>(static_cast<void*>(&x));

Any object in C++ can be reinterpreted as an array of bytes. If you want to actually make a copy of the bytes into a separate array, you can use std::copy:

C++ 中的任何对象都可以重新解释为字节数组。如果要实际将字节副本复制到单独的数组中,可以使用std::copy

int x;
char bytes[sizeof x];
std::copy(static_cast<const char*>(static_cast<const void*>(&x)),
          static_cast<const char*>(static_cast<const void*>(&x)) + sizeof x,
          bytes);

Neither of these methods takes byte ordering into account, but since you can reinterpret the intas an array of bytes, it is trivial to perform any necessary modifications yourself.

这些方法都没有考虑字节顺序,但是由于您可以将 重新解释int为字节数组,因此您自己执行任何必要的修改是微不足道的。

回答by NullData

Another useful way of doing it that I use is unions:

我使用的另一种有用的方法是联合:

union byteint
{
    byte b[sizeof int];
    int i;
};
byteint bi;
bi.i = 1337;
for(int i = 0; i<4;i++)
    destination[i] = bi.b[i];

This will make it so that the byte array and the integer will "overlap"( share the same memory ). this can be done with all kinds of types, as long as the byte array is the same size as the type( else one of the fields will not be influenced by the other ). And having them as one object is also just convenient when you have to switch between integer manipulation and byte manipulation/copying.

这将使字节数组和整数“重叠”(共享相同的内存)。这可以用各种类型来完成,只要字节数组的大小与类型相同(否则其中一个字段不会受到另一个字段的影响)。当您必须在整数操作和字节操作/复制之间切换时,将它们作为一个对象也很方便。

回答by BlackBear

You can get individual bytes with anding and shifting operations:

您可以使用 anding 和 shift 操作获取单个字节:

byte1 =  nint & 0x000000ff
byte2 = (nint & 0x0000ff00) >> 8
byte3 = (nint & 0x00ff0000) >> 16
byte4 = (nint & 0xff000000) >> 24

回答by James Kanze

std::vector<unsigned char> intToBytes(int value)
{
    std::vector<unsigned char> result;
    result.push_back(value >> 24);
    result.push_back(value >> 16);
    result.push_back(value >>  8);
    result.push_back(value      );
    return result;
}

回答by Sarath AK

Int to byte and vice versa.

整数到字节,反之亦然。

unsigned char bytes[4];
unsigned long n = 1024;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);


int num = 0;
for(int i = 0; i < 4; i++)
 {
 num <<= 8;
 num |= bytes[i];
 }


printf("number %d",num);

回答by SportySpice

An int (or any other data type for that matter) is already stored as bytes in memory. So why not just copy the memory directly?

int(或任何其他数据类型)已经作为字节存储在内存中。那么为什么不直接复制内存呢?

memcpy(arrayOfByte, &x, sizeof x);

A simple elegant one liner that will also work with any other data type.

一个简单优雅的单行代码,也适用于任何其他数据类型。





If you need the bytes reversed you can use std::reverse

如果您需要反转字节,您可以使用 std::reverse

memcpy(arrayOfByte, &x, sizeof x);
std::reverse(arrayOfByte, arrayOfByte + sizeof x);

or better yet, just copy the bytes in reverse to begin with

或者更好的是,只需反向复制字节即可

BYTE* p = (BYTE*) &x;
std::reverse_copy(p, p + sizeof x, arrayOfByte);


If you don't want to make a copy of the data at all, and just have its byte representation

如果您根本不想复制数据,而只想使用其字节表示

BYTE* bytes = (BYTE*) &x;

回答by jberg

return ((byte[0]<<24)|(byte[1]<<16)|(byte[2]<<8)|(byte[3]));

:D

:D

回答by NutCracker

I know this question already has answers but I will give my solution to this problem. I am using template function and integer constraint on it.

我知道这个问题已经有了答案,但我会给出我对这个问题的解决方案。我正在使用模板函数和整数约束。

Here is my solution:

这是我的解决方案:

#include <type_traits>
#include <vector>

template <typename T,
          typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
std::vector<uint8_t> splitValueToBytes(T const& value)
{
    std::vector<uint8_t> bytes;

    for (size_t i = 0; i < sizeof(value); i++)
    {
        uint8_t byte = value >> (i * 8);
        bytes.insert(bytes.begin(), byte);
    }

    return bytes;
}

回答by canellas

I hope mine helps

我希望我的帮助

template <typename t_int>
std::array<uint8_t, sizeof (t_int)> int2array(t_int p_value) {
    static const uint8_t _size_of (static_cast<uint8_t>(sizeof (t_int)));
    typedef std::array<uint8_t, _size_of> buffer;
    static const std::array<uint8_t, 8> _shifters = {8*0, 8*1, 8*2, 8*3, 8*4, 8*5, 8*6, 8*7};

    buffer _res;
    for (uint8_t _i=0; _i < _size_of; ++_i) {
        _res[_i] = static_cast<uint8_t>((p_value >> _shifters[_i]));
    }
    return _res;
}