Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break an int into two chars [duplicate]

Tags:

java

c

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?

like image 906
Skeith Avatar asked Nov 10 '22 21:11

Skeith


2 Answers

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;
like image 55
Rewind Avatar answered Nov 14 '22 22:11

Rewind


You can also use BigInteger.

    byte[] bytes = BigInteger.valueOf(x).toByteArray();
    int y = new BigInteger(bytes).intValue();
like image 29
OldCurmudgeon Avatar answered Nov 14 '22 23:11

OldCurmudgeon