Dotnet Hex String for Java

You have a problem, like this post: How to read .NET Guid in Java UUID .

Also, I get a hexadecimal string from a remote svc, formatted as follows: ABCDEFGH-IJKL-MNOP-QRST-123456.

I need to map the GUID.ToByteArray () generated byte array of .net bytes GH-EF-CD-AB-KL-IJ-OP-MN- QR- ST-12-34-56in Java for hash purposes.

I was a little confused how to make out this. I cut the part QRST-123456and maybe use something like Commons IO EndianUtils on the other hand and then stitch 2 arrays together again? Seems too complicated. I can change the order of the lines, but I did not need to do any of this. Mr. Google doesn't want to help me either ...

By the way, what is the logic in Little Endian Land that keeps the last 6 char unchanged?


Yes, for reference, here is what I did {sorry for the "answer", but could not format it correctly in the comment}:

String s = "3C0EA2F3-B3A0-8FB0-23F0-9F36DEAA3F7E";
String[] splitz = s.split("-");
String rebuilt = "";
for (int i = 0; i < 3; i++) { 
  // Split into 2 char chunks. '..' = nbr of chars in chunks 
  String[] parts = splitz[i].split("(?<=\\G..)"); 
  for (int k = parts.length -1; k >=0; k--) {
   rebuilt += parts[k]; 
  } 
 } 
 rebuilt += splitz[3]+splitz[4];

I know it is hacked, but it will work for testing.

+3
source share
2 answers

Make it byte [] and skip the first 3 bytes:

package guid;
import java.util.Arrays;

public class GuidConvert {

    static byte[] convertUuidToBytes(String guid) {
        String hexdigits = guid.replaceAll("-", "");
        byte[] bytes = new byte[hexdigits.length()/2];
        for (int i = 0; i < bytes.length; i++) {
            int x = Integer.parseInt(hexdigits.substring(i*2, (i+1)*2), 16);
            bytes[i] = (byte) x;
        }
        return bytes;
    }

    static String bytesToHexString(byte[] bytes) {
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes) {
            int i = b >= 0 ? b : (int) b + 256;
            buf.append(Integer.toHexString(i / 16));
            buf.append(Integer.toHexString(i % 16));
        }
        return buf.toString();
    }

    public static void main(String[] args) {
        String guid = "3C0EA2F3-B3A0-8FB0-23F0-9F36DEAA3F7E";
        byte[] bytes = convertUuidToBytes(guid);
        System.err.println("GUID  = "+ guid);
        System.err.println("bytes = "+ bytesToHexString(bytes));
        byte[] tail = Arrays.copyOfRange(bytes, 3, bytes.length);
        System.err.println("tail  =       "+ bytesToHexString(tail));
    }
}
+1
source

The last group of 6 bytes is not reversed because it is an array of bytes. The first four groups are reversed, as they are a four-byte integer followed by three two-byte integers.

0
source

All Articles