How to split int into two characters

This is an outdated system, so please do not tell me what I'm trying to do, this is wrong. It should be like that.

I have an array of bytes where the date is placed in a sequential manner. This is normal until I want to keep the value above 255. For this, I need to use 2 bytes as a 16-bit value.

So I need to convert int to two characters, and then two characters back to int.

One program is in C and the other is in Java, and they exchange data through an array of bytes.

It seems to me that the problem has been fixed a long time ago, so I wonder if there is a function for this in the Java and C libraries. If not, is there an easy way to do the conversion?

+4
source share
3 answers

You can also use BigInteger.

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

As far as I can see, you are just doing basic math.

I have not programmed c for some time, so ignore 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 type upper_char and lower_char as usual.

[Edit

And to go 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;

]

Thus, 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 recovery

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;
0
source

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 >> 8) & 0xFF;

/* back */

value = chars[0] | (chars[1] << 8);
-1
source

Source: https://habr.com/ru/post/1568358/


All Articles