This a legacy system so please don't tell me what I'm trying to do is wrong. It has to be this way.
I have a byte array where date is put in a sequential manner. This is fine until I want to store a value above 255. To do this I need to use 2 bytes as a 16 bit value.
So I need to convert an int into two chars and then the two chars back into an int.
One program is in C and the other in Java and they communicate through a byte array.
This seems to me like a problem that should have been fixed a long time ago so I'm wondering if there is a function for doing this in the Java and C libraries. If not, is there an easy way of making the conversion?
As far as I can see you are just doing base 256 maths.
I have not programmed c for a little while so disregard any old terminology;
int original_number = 300; // A number over 255
char higher_char, lower_char; // the 2 numbers/chars you are trying to get
higher_char = original_number / 256;
lower_char = original_number % 256;
and then just print higher_char and lower_char as normal.
[Edit
And to convert back.
char higher_char, lower_char; // The two chars you have in order
int number_to_restore; // The original number you are trying to get back to
number_to_restore = higher_char * 256 + lower_char;
]
So using binary operators this becomes:
int mask = 0xFF;
int original_number = 300; // A number over 255
char higher_char, lower_char; // the 2 numbers/chars you are trying to get
higher_char = (original_number >> 8) & mask;
lower_char = original_number & mask;
and the restore
char higher_char, lower_char; // The two chars you have in order
int number_to_restore; // The original number you are trying to get back to
number_to_restore = (higher_char << 8) | lower_char;
You can also use BigInteger
.
byte[] bytes = BigInteger.valueOf(x).toByteArray();
int y = new BigInteger(bytes).intValue();
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