Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ int to byte array

Tags:

c++

arrays

int

byte

I have this method in my java code which returns byte array for given 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++?

like image 876
justme_ Avatar asked Apr 07 '11 18:04

justme_


People also ask

How to convert an integer into a specific byte array in c++?

We split the input integer (5000) into each byte by using the >> operator. The second operand represents the lowest bit index for each byte in the array. To obtain the 8 least significant bits for each byte, we & the result with 0xFF . Finally, we print each byte using the print function.

Can we convert int to byte?

An int value can be converted into bytes by using the method int. to_bytes().

Can we typecast array in C?

In C, you can uses casts to convert between types. That's not called a typecast, however. The C language specification generally frowns upon type punning, where you access an object of one type through a pointer of another type. There are a handful of exceptions.

What is byte array?

A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.


1 Answers

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:

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 int as an array of bytes, it is trivial to perform any necessary modifications yourself.

like image 73
James McNellis Avatar answered Sep 20 '22 03:09

James McNellis