Send byte [] to String from Java to C program

I need to put my Java information into a string, so I use the constructor String(byte[] arrB)

. Now this information is sent to the C program as a type char*

. Now I need to get back the original bytes as I believe they were encoded during Java creation String

.

How do I do this in a C program?

So, on the C side, I have these bytes:

7e 53 e9 94 d4 46 f5 7c 66 cf 85 34 18 5a ff 6 2d a3 89 48 d2 e4 46 b8 6b 43 ec 64 3a 67 f9 2 6d 12 ac e7 0 c4 99 52 68 76 76 77 12 2 de 7d 5b e7 4e 5 6 73 f4 fc 91 54 12 71 64 7a 25 3d

They are in char*

, but Java reach as String and String:

7E 53 EF BF BD EF BF BD 46 EF BF BD 7C 66 CF 85 34 18 5A EF BF BD 06 2D EF BF BD EF BF BD 48 EF BF BD EF BF BD 46 EF BF BD 6B 43 EF BF BD 64 3A 67 EF BF BD 02 6D 12 EF BF BD EF BF BD

As you can see there are many similarities ...

+3


source to share


1 answer


Since you do not give details about the transfer between java and C, I cannot provide you with a complete answer, only guesses. (please indicate code)

First points: As Scary Wombat says, if you want to send data to C, don't use encoding, juste send bytes.

Premise 1: Coding is not the same

When you encode your bytes to String, you will use the default encoding. As the javadoc says:

Creates a new {@code String} by decoding the specified array of bytes using the platform's default encoding

public String (byte bytes [])

If you need to send String to char *, define encoding on both sides:

String.getBytes("UTF-8)". 

      



If your java and c part is using a different encoding, you will get a difference in the results.

Assumption 2: Added a null byte If the size is different (1 byte) it is probably a null byte at the end of your char *.

Assumption 3: you are reading multiple char that come out of your array

How did you go about initializing your char *? Did you have malloc? Fixed size buffer? It may be wrong and you are reading other data belonging to another buffer / variable / ....

Assumption 3 ': Miss init char *, you are just reading the initial value of the buffer.

Don't forget to allocate memory for your structure: Two examples of how to allocate memory for a structure and when

0


source







All Articles