字符串Sid到字节数组Sid
/*from nowjava.com*/ //package com.nowjava; import java.io.ByteArrayOutputStream; import java.util.StringTokenizer; public class Main { public static byte[] stringSidToByteArraySid(String SID) { ByteArrayOutputStream obyte = new ByteArrayOutputStream(); StringTokenizer tokens = new StringTokenizer(SID, "-"); int idx = 0, sub_authorities_sz = 0; long[] sub_authorities_buff = new long[8]; while (tokens.hasMoreElements()) { String sval = (String) tokens.nextElement(); long val = 0; try { val = Long.parseLong(sval); } catch (NumberFormatException e) { idx++; continue; // skip S./** 来 自 n o w j a v a . c o m - 时代Java**/ } // SID revision if (idx == 1) obyte.write((byte) (val & 0xFF)); // 48-bit SID authority else if (idx == 2) { byte[] bval = longToByteArray(val); obyte.write(bval[0]); obyte.write(bval[1]); obyte.write(bval[2]); obyte.write(bval[3]); obyte.write(bval[4]); obyte.write(bval[5]); // N number of 32-bit SID sub-authorities. } else { sub_authorities_buff[idx - 3] = val; sub_authorities_sz++; } idx++; } // Write the number of SID sub-authorities. obyte.write((byte) sub_authorities_sz); // Write each SID sub-authority. for (int i = 0; i < sub_authorities_sz; i++) { byte[] bval = longToByteArray(sub_authorities_buff[i]); obyte.write(bval[0]); obyte.write(bval[1]); obyte.write(bval[2]); obyte.write(bval[3]); } return obyte.toByteArray(); } private static byte[] longToByteArray(long value) { byte[] result = new byte[8]; // FYI - The effect of this operation is to break // down the long into an array of eight bytes. // // What's going on: The FF selects selects the byte // of interest within value. The the >> shifts the // target bits to the right the desired result. The // shift ensures the result will fit into a single // 8-bit byte. Depending upon the byte of interest // it must be shifted appropriately so it's always // in the lower-order 8-bits. result[0] = (byte) (value & 0x00000000000000FFL); result