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++?
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.
An int value can be converted into bytes by using the method int. to_bytes().
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With