'How to break an int into two chars [duplicate]

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?



Solution 1:[1]

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;

Solution 2:[2]

You can also use BigInteger.

    byte[] bytes = BigInteger.valueOf(x).toByteArray();
    int y = new BigInteger(bytes).intValue();

Solution 3:[3]

This is how i would do it in C

uint16_t value;
uint8_t  chars[2];

value = 280;

/* to bytes array */

chars[0] = value & 0xFF;
chars[1] = (value >> CHAR_BIT) & 0xFF;

/* back */

value = chars[0] | (chars[1] << CHAR_BIT);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 OldCurmudgeon
Solution 3