简体   繁体   中英

integer to byte in Java and C++

In my C++ code, I need to convert an int and put it inside a byte. I represent a byte using a char . In my java code, I should read this byte (it is sent over the network), and I should get the appropriate int from that byte (the one that I sent).

I should mention that this byte is less than 15, so one byte would be sufficient for it

However, the Java code is reading negative numbers in some attempts, and when I tried other ways it gave me totally different numbers. I suspect it is a problem of big/little endian.

What I've tried:

// C++
char bytes[255];
bytes[0] = myInt; // attempt 1
bytes[0] = myInt & 0xFF; // attempt 2
// ... send the byte array over the network

// JAVA
// receive the byte
int readInt = bytes[0]; //attempt 1
int readInt = bytes[0] & 0xFF; // attempt2

How should I properly do this, given that the two applications (C++ side and JAVA side) will run on the same ubuntu machine?

Further edit: int readInt = bytes[0] & 0xFF should work.

for (int i = 0; i < 256; i++) {
    byte b = (byte) i;
    int j = b & 0xFF;
    System.out.println("The byte is " + b + " and the int is " + j);
}

Gives:

The byte is 0 and the int is 0
The byte is 1 and the int is 1
...
The byte is 126 and the int is 126
The byte is 127 and the int is 127
The byte is -128 and the int is 128
The byte is -127 and the int is 129
...
The byte is -2 and the int is 254
The byte is -1 and the int is 255

Edit (after comment above): 7 = 0000 0111 and -32 = 1110 0000 (= 224 as int) The issue appears to be some kind of mirroring flip.

and 170 = 1010 1010 (= -86 as Java byte) which doesn't make sense to me because how did 3 on bits turn into 4 and spread out.

Note: it's never an endian issue. Only if you work low level or make your own arrays of bytes to represent one number, it may be an endian issue.

It is only one byte now, so no endian issue.

Try to use unsigned int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM