Jave Code Examples for 'convert bytes'

60 Jave code examples are found related to "convert bytes". These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Project: gcs   Author: richardwilkes   File: BaseFont.java    License: Mozilla Public License 2.0 7 votes vote down vote up
/**
 * Converts a <CODE>String</CODE> to a </CODE>byte</CODE> array according to the font's
 * encoding.
 *
 * @param text the <CODE>String</CODE> to be converted
 * @return an array of <CODE>byte</CODE> representing the conversion according to the font's
 *         encoding
 */
byte[] convertToBytes(String text) {
    if (directTextToByte) {
        return PdfEncodings.convertToBytes(text, null);
    }
    if (specialMap != null) {
        byte[] b = new byte[text.length()];
        int ptr = 0;
        int length = text.length();
        for (int k = 0; k < length; ++k) {
            char c = text.charAt(k);
            if (specialMap.containsKey(c)) {
                b[ptr++] = (byte) specialMap.get(c);
            }
        }
        if (ptr < length) {
            byte[] b2 = new byte[ptr];
            System.arraycopy(b, 0, b2, 0, ptr);
            return b2;
        } else {
            return b;
        }
    }
    return PdfEncodings.convertToBytes(text, encoding);
}
 
Example 2
Project: aion   Author: aionnetwork   File: HexConvert.java    License: MIT License 6 votes vote down vote up
public static byte[] hexStringToBytes(String s) {

        if (s == null) {
            return ZERO_BYTE_ARRAY;
        }
        if (s.startsWith("0x")) {
            s = s.substring(2);
        }
        if ((s.length() & 1) == 1) {
            s = "0" + s;
        }

        int len = s.length();
        byte[] data = new byte[len >> 1];
        for (int i = 0; i < len; i += 2) {
            data[i >> 1] =
                    (byte)
                            ((Character.digit(s.charAt(i), 16) << 4)
                                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
 
Example 3
Project: hottub   Author: dsrg-uoft   File: Password.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Change a password read from Console.readPassword() into
 * its original bytes.
 *
 * @param pass a char[]
 * @return its byte[] format, similar to new String(pass).getBytes()
 */
private static byte[] convertToBytes(char[] pass) {
    if (enc == null) {
        synchronized (Password.class) {
            enc = sun.misc.SharedSecrets.getJavaIOAccess()
                    .charset()
                    .newEncoder()
                    .onMalformedInput(CodingErrorAction.REPLACE)
                    .onUnmappableCharacter(CodingErrorAction.REPLACE);
        }
    }
    byte[] ba = new byte[(int)(enc.maxBytesPerChar() * pass.length)];
    ByteBuffer bb = ByteBuffer.wrap(ba);
    synchronized (enc) {
        enc.reset().encode(CharBuffer.wrap(pass), bb, true);
    }
    if (bb.position() < ba.length) {
        ba[bb.position()] = '\n';
    }
    return ba;
}
 
Example 4
Project: tajo   Author: apache   File: AvroScanner.java    License: Apache License 2.0 6 votes vote down vote up
private Datum convertBytes(Object value, TajoDataTypes.Type tajoType,
                           DataType dataType) {
  ByteBuffer buffer = (ByteBuffer)value;
  byte[] bytes = new byte[buffer.capacity()];
  buffer.get(bytes, 0, bytes.length);
  switch (tajoType) {
    case PROTOBUF:
      try {
        ProtobufDatumFactory factory =
            ProtobufDatumFactory.get(dataType.getCode());
        Message.Builder builder = factory.newBuilder();
        builder.mergeFrom(bytes);
        return ProtobufDatumFactory.createDatum(builder);
      } catch (InvalidProtocolBufferException e) {
        throw new RuntimeException(e);
      }
    default:
      return new BlobDatum(bytes);
  }
}
 
Example 5
Project: Android-UtilCode   Author: hoangkien0705   File: ConvertUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * bits转bytes
 *
 * @param bits 二进制
 * @return bytes
 */
public static byte[] bits2Bytes(String bits) {
    int lenMod = bits.length() % 8;
    int byteLen = bits.length() / 8;
    // 不是8的倍数前面补0
    if (lenMod != 0) {
        for (int i = lenMod; i < 8; i++) {
            bits = "0" + bits;
        }
        byteLen++;
    }
    byte[] bytes = new byte[byteLen];
    for (int i = 0; i < byteLen; ++i) {
        for (int j = 0; j < 8; ++j) {
            bytes[i] <<= 1;
            bytes[i] |= bits.charAt(i * 8 + j) - '0';
        }
    }
    return bytes;
}
 
Example 6
Project: rdf4j   Author: eclipse   File: IDFile.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Long[] convertBytesToLongs(byte[] bytes) {
	Long[] cacheLine;
	cacheLine = new Long[cacheLineSize];
	for (int i = 0; i < bytes.length; i += ITEM_SIZE) {
		long l = ((long) (bytes[i + 0] & 0xff) << 56)
				| ((long) bytes[i + 1] & 0xff) << 48
				| ((long) bytes[i + 2] & 0xff) << 40
				| ((long) bytes[i + 3] & 0xff) << 32
				| ((long) bytes[i + 4] & 0xff) << 24
				| ((long) bytes[i + 5] & 0xff) << 16
				| ((long) bytes[i + 6] & 0xff) << 8
				| ((long) bytes[i + 7] & 0xff);

		cacheLine[(int) (i / ITEM_SIZE)] = l;
	}
	return cacheLine;
}
 
Example 7
Project: DevUtils   Author: afkT   File: ConvertUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * byte[] 转换 char[], 并且进行补码
 * @param data byte[]
 * @return char[]
 */
public static char[] bytesToChars(final byte[] data) {
    if (data == null) return null;
    int len = data.length;
    if (len == 0) return null;
    try {
        char[] chars = new char[len];
        for (int i = 0; i < len; i++) {
            chars[i] = (char) (data[i] & 0xff);
        }
        return chars;
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "bytesToChars");
    }
    return null;
}
 
Example 8
Project: DevUtils   Author: afkT   File: ConvertUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Object 转为 byte[]
 * @param object Object
 * @return byte[]
 */
public static byte[] objectToBytes(final Object object) {
    if (object == null) return null;
    ObjectOutputStream oos = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        return baos.toByteArray();
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "objectToBytes");
    } finally {
        if (oos != null) {
            try {
                oos.close();
            } catch (Exception e) {
            }
        }
    }
    return null;
}
 
Example 9
Project: DevUtils   Author: afkT   File: ConvertUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * char[] 转换 byte[]
 * @param data char[]
 * @return byte[]
 */
public static byte[] charsToBytes(final char[] data) {
    if (data == null) return null;
    int len = data.length;
    if (len == 0) return null;
    try {
        byte[] bytes = new byte[len];
        for (int i = 0; i < len; i++) {
            bytes[i] = (byte) (data[i]);
        }
        return bytes;
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "charsToBytes");
    }
    return null;
}
 
Example 10
Project: jitsi   Author: jitsi   File: ImageUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a bytes of the given <tt>scaledImage</tt>.
 * @param scaledImage the image to scale
 * @return a byte array containing the scaled image
 */
private static byte[] convertImageToBytes(BufferedImage scaledImage)
{
    byte[] scaledBytes = null;

    if (scaledImage != null)
    {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        try
        {
            ImageIO.write(scaledImage, "png", outStream);
            scaledBytes = outStream.toByteArray();
        }
        catch (IOException e)
        {
            if (logger.isDebugEnabled())
                logger.debug("Could not scale image in bytes.", e);
        }

    }

    return scaledBytes;
}
 
Example 11
Project: netbeans   Author: apache   File: BinaryToStringConverter.java    License: Apache License 2.0 6 votes vote down vote up
public static byte[] convertBitStringToBytes(String s) throws DBException {
    int shtBits = s.length() % 8;
    s = (shtBits > 0 ? "00000000".substring(0, 8 - shtBits) + s : s); // NOI18N

    byte[] buf = new byte[s.length() / 8];

    int bit = 0, index = 0;
    for (int i = 0; i < s.length(); i++) {
        if ('1' == s.charAt(i)) { // NOI18N
            int b = 1 << (7 - bit);
            buf[index] |= b;
        } else if ('0' != s.charAt(i)) { // NOI18N
            throw new DBException(NbBundle.getMessage(BinaryToStringConverter.class, "BinaryToStringConverter_InvalidBitFormat", s.charAt(i), i)); // NOI18N
        }
        bit++;
        if (bit > 7) {
            bit = 0;
            index++;
        }
    }
    return buf;
}
 
Example 12
Project: gemfirexd-oss   Author: gemxd   File: DiskStoreImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Given a BytesAndBits object convert it to the relevant Object (deserialize
 * if necessary) and return the object
 * 
 * @param bb
 * @return the converted object
 */
static Object convertBytesAndBitsIntoObject(BytesAndBits bb) {
  byte[] bytes = bb.getBytes();
  Object value;
  if (EntryBits.isInvalid(bb.getBits())) {
    value = Token.INVALID;
  } else if (EntryBits.isSerialized(bb.getBits())) {
    value = DiskEntry.Helper
        .readSerializedValue(bytes, bb.getVersion(), null, true);
  } else if (EntryBits.isLocalInvalid(bb.getBits())) {
    value = Token.LOCAL_INVALID;
  } else if (EntryBits.isTombstone(bb.getBits())) {
    value = Token.TOMBSTONE;
  } else {
    value = DiskEntry.Helper.readRawValue(bytes, bb.getVersion(), null);
  }
  return value;
}
 
Example 13
Project: reladomo   Author: goldmansachs   File: MithraNotificationEventManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] convertObjectToBytes(Object data)
        throws IOException
{
    byte[] pileOfBytes = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream(200);
    synchronized (this.lz4BlockOutputStream)
    {
        lz4BlockOutputStream.reset(bos);
        ObjectOutputStream oos = new ObjectOutputStream(lz4BlockOutputStream);
        oos.writeObject(data);
        oos.flush();
        lz4BlockOutputStream.finish();
        bos.flush();
        pileOfBytes = bos.toByteArray();
        bos.close();
    }
    return pileOfBytes;
}
 
Example 14
Project: Pistachio   Author: lyogavin   File: Convert.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Performs conversion of a long value to a byte array representation.
 *
 * @see #bytesToLong(byte[])
 */
public static byte[] longToBytes(long value) {

    // A long value is 8 bytes in length.
    byte[] bytes = new byte[8];

    // Convert and copy value to byte array:
    // -- Cast long to a byte to retrieve least significant byte;
    // -- Left shift long value by 8 bits to isolate next byte to be converted;
    // -- Repeat until all 8 bytes are converted (long = 64 bits).
    // Note: In the byte array, the least significant byte of the long is held in
    // the highest indexed array bucket.

    for (int i = 0; i < bytes.length; i++) {
        bytes[(bytes.length - 1) - i] = (byte) value;
        value >>>= 8;
    }

    return bytes;
}
 
Example 15
Project: Pistachio   Author: lyogavin   File: Convert.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Performs conversion of a byte array to a long representation.
 *
 * @see #longToBytes(long)
 */
public static long bytesToLong(byte[] value) {

    long longValue = 0L;

    // See method convertLongToBytes(long) for algorithm details.
    if (ArrayUtils.isNotEmpty(value)) {
        for (int i = 0; i < value.length; i++) {
            // Left shift has no effect thru first iteration of loop.
            longValue <<= 8;
            longValue ^= value[i] & 0xFF;
        }
    }

    return longValue;
}
 
Example 16
Project: spring-analysis-note   Author: Vip-Augus   File: MappingJackson2MessageConverter.java    License: MIT License 6 votes vote down vote up
/**
 * Convert a BytesMessage to a Java Object with the specified type.
 * @param message the input message
 * @param targetJavaType the target type
 * @return the message converted to an object
 * @throws JMSException if thrown by JMS
 * @throws IOException in case of I/O errors
 */
protected Object convertFromBytesMessage(BytesMessage message, JavaType targetJavaType)
		throws JMSException, IOException {

	String encoding = this.encoding;
	if (this.encodingPropertyName != null && message.propertyExists(this.encodingPropertyName)) {
		encoding = message.getStringProperty(this.encodingPropertyName);
	}
	byte[] bytes = new byte[(int) message.getBodyLength()];
	message.readBytes(bytes);
	if (encoding != null) {
		try {
			String body = new String(bytes, encoding);
			return this.objectMapper.readValue(body, targetJavaType);
		}
		catch (UnsupportedEncodingException ex) {
			throw new MessageConversionException("Cannot convert bytes to String", ex);
		}
	}
	else {
		// Jackson internally performs encoding detection, falling back to UTF-8.
		return this.objectMapper.readValue(bytes, targetJavaType);
	}
}
 
Example 17
Project: elasticsearch-hadoop   Author: elastic   File: StormTupleBytesConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void convert(Object from, BytesArray to) {
    Assert.isTrue(from == null || from instanceof Tuple,
            String.format("Unexpected object type, expecting [%s], given [%s]", Tuple.class, from.getClass()));

    // handle common cases
    Tuple tuple = (Tuple) from;

    if (tuple == null || tuple.size() == 0) {
        to.bytes("{}");
        return;
    }
    Assert.isTrue(tuple.size() == 1, "When using JSON input, only one field is expected");

    super.convert(tuple.getValue(0), to);
}
 
Example 18
Project: incubator-gobblin   Author: apache   File: ObjectStoreDeleteConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void convertBytesObjId() throws Exception {
  WorkUnitState wu = new WorkUnitState();
  wu.setProp(ObjectStoreDeleteConverter.OBJECT_ID_FIELD, "objectId");
  ObjectStoreDeleteConverter converter = new ObjectStoreDeleteConverter();
  converter.init(wu);
  Schema schema =
      new Schema.Parser()
          .parse("{ \"type\" : \"record\", \"name\" : \"test_schema\", \"namespace\" : \"com.gobblin.test\", "
              + "\"fields\" : [ { \"name\" : \"objectId\", \"type\" : \"bytes\"} ], \"doc:\" : \"\" }");
  GenericRecord datum = new GenericData.Record(schema);
  String objId = "abcd";
  datum.put("objectId", objId.getBytes());

  Assert
      .assertEquals(Iterables.getFirst(converter.convertRecord(converter.convertSchema(schema, wu), datum, wu), null)
          .getObjectId(), objId.getBytes());
}
 
Example 19
Project: xDrip   Author: NightscoutFoundation   File: JoH.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static byte[] convertPinToBytes(String pin) {
    if (pin == null) {
        return null;
    }
    byte[] pinBytes;
    try {
        pinBytes = pin.getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
        Log.e(TAG, "UTF-8 not supported?!?");  // this should not happen
        return null;
    }
    if (pinBytes.length <= 0 || pinBytes.length > 16) {
        return null;
    }
    return pinBytes;
}
 
Example 20
Project: xDrip-plus   Author: jamorham   File: JoH.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static byte[] convertPinToBytes(String pin) {
    if (pin == null) {
        return null;
    }
    byte[] pinBytes;
    try {
        pinBytes = pin.getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
        Log.e(TAG, "UTF-8 not supported?!?");  // this should not happen
        return null;
    }
    if (pinBytes.length <= 0 || pinBytes.length > 16) {
        return null;
    }
    return pinBytes;
}
 
Example 21
Project: jrpip   Author: goldmansachs   File: ByteUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Object convertBytesToObject(byte[] input) throws IOException, ClassNotFoundException
{
    ByteArrayInputStream bis = new ByteArrayInputStream(input);
    FixedInflaterInputStream zis = null;
    Object result = null;
    try
    {
        zis = new FixedInflaterInputStream(bis);
        ObjectInputStream ois = new ObjectInputStream(zis);
        result = ois.readObject();
        ois.close();
        zis.finish();
        zis.close();
        zis = null;
        bis.close();
    }
    finally
    {
        if (zis != null)
        {
            zis.finish();
        }
    }
    return result;
}
 
Example 22
Project: julongchain   Author: JulongChain   File: Convert.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 字符数组转换16进制字符串
 * @param src
 * @return
 */
public static String bytesToHexString(byte[] src){
    StringBuilder stringBuilder = new StringBuilder("");
    if (src == null || src.length <= 0) {
        return null;
    }
    for (int i = 0; i < src.length; i++) {
        int v = src[i] & 0xFF;
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {
            stringBuilder.append(0);
        }
        stringBuilder.append(hv);
    }
    return stringBuilder.toString();
}
 
Example 23
Project: riposte   Author: Nike-Inc   File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static @Nullable String convertRawBytesToString(
    @NotNull Charset contentCharset,
    @Nullable byte[] rawBytes
) {
    //noinspection ConstantConditions
    if (contentCharset == null) {
        throw new IllegalArgumentException("contentCharset cannot be null");
    }

    if (rawBytes == null) {
        return null;
    }

    if (rawBytes.length == 0) {
        return "";
    }

    String rawString = new String(rawBytes, contentCharset);
    // UTF-16 can insert byte order mark characters when splicing together multiple chunks. Remove them
    rawString = rawString.replace("\uFEFF", "");
    return rawString;
}
 
Example 24
Project: vjtools   Author: vipshop   File: UnitConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void convertSizeBytes() {
	assertThat(UnitConverter.toBytes("12345")).isEqualTo(12345);
	assertThat(UnitConverter.toBytes("12b")).isEqualTo(12);
	assertThat(UnitConverter.toBytes("12k")).isEqualTo(12 * 1024);
	assertThat(UnitConverter.toBytes("12M")).isEqualTo(12 * 1024 * 1024);

	assertThat(UnitConverter.toBytes("12G")).isEqualTo(12l * 1024 * 1024 * 1024);
	assertThat(UnitConverter.toBytes("12T")).isEqualTo(12l * 1024 * 1024 * 1024 * 1024);

	try {
		UnitConverter.toBytes("12x");
		fail("should fail");
	} catch (Throwable t) {
		assertThat(t).isInstanceOf(IllegalArgumentException.class);
	}

	try {
		UnitConverter.toBytes("a12");
		fail("should fail");
	} catch (Throwable t) {
		assertThat(t).isInstanceOf(IllegalArgumentException.class);
	}
}
 
Example 25
Project: hdw-dubbo   Author: JacksonTu   File: CHexConvert.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * bytes字符串转换为Byte值
 *
 * @param src String Byte字符串,每个Byte之间没有分隔符(字符范围:0-9 A-F)
 * @return byte[]
 */
public static byte[] hexStr2Bytes(String src) {
    /*对输入值进行规范化整理*/
    src = src.trim().replace(" ", "").toUpperCase(Locale.US);
    //处理值初始化
    int m = 0, n = 0;
    int iLen = src.length() / 2; //计算长度
    byte[] ret = new byte[iLen]; //分配存储空间

    for (int i = 0; i < iLen; i++) {
        m = i * 2 + 1;
        n = m + 1;
        ret[i] = (byte) (Integer.decode("0x" + src.substring(i * 2, m) + src.substring(m, n)) & 0xFF);
    }
    return ret;
}
 
Example 26
Project: metadata-extractor   Author: drewnoakes   File: TagDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Takes a series of 4 bytes from the specified offset, and converts these to a
 * well-known version number, where possible.
 * <p>
 * Two different formats are processed:
 * <ul>
 * <li>[30 32 31 30] -&gt; 2.10</li>
 * <li>[0 1 0 0] -&gt; 1.00</li>
 * </ul>
 *
 * @param components  the four version values
 * @param majorDigits the number of components to be
 * @return the version as a string of form "2.10" or null if the argument cannot be converted
 */
@Nullable
public static String convertBytesToVersionString(@Nullable int[] components, final int majorDigits)
{
    if (components == null)
        return null;
    StringBuilder version = new StringBuilder();
    for (int i = 0; i < 4 && i < components.length; i++) {
        if (i == majorDigits)
            version.append('.');
        char c = (char)components[i];
        if (c < '0')
            c += '0';
        if (i == 0 && c == '0')
            continue;
        version.append(c);
    }
    return version.toString();
}
 
Example 27
Project: protools   Author: SeanDragon   File: ToolConvert.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * hexString转byteArr <p>例如:</p> hexString2Bytes("00A8") returns { 0, (byte) 0xA8 }
 *
 * @param hexString
 *         十六进制字符串
 *
 * @return 字节数组
 */
public static byte[] hexString2Bytes(String hexString) {
    if (ToolStr.isSpace(hexString)) {
        return null;
    }
    int len = hexString.length();
    if (len % 2 != 0) {
        hexString = "0" + hexString;
        len = len + 1;
    }
    char[] hexBytes = hexString.toUpperCase().toCharArray();
    byte[] ret = new byte[len >> 1];
    for (int i = 0; i < len; i += 2) {
        ret[i >> 1] = (byte) (hex2Dec(hexBytes[i]) << 4 | hex2Dec(hexBytes[i + 1]));
    }
    return ret;
}
 
Example 28
Project: snowblossom   Author: snowblossomcoin   File: Duck32.java    License: Apache License 2.0 6 votes vote down vote up
private static ByteString convertBase32ToBytes(String encoding)
  throws ValidationException
{
  BigInteger big = new BigInteger(convertBech32ToBase32(encoding), 32);
  byte[] data = big.toByteArray();

  int data_size=HASH_BYTES + Globals.ADDRESS_SPEC_HASH_LEN;


  // Helpful biginteger might throw an extra zero byte on the front to show positive sign
  // or it might start with a lot of zeros and be short so add them back in
  int start = data.length - data_size;
  if (start >= 0)
  {
    return ByteString.copyFrom(data, start, Globals.ADDRESS_SPEC_HASH_LEN + HASH_BYTES);
  }
  else
  {
    byte[] zeros = new byte[data_size];
    int needed_zeros = data_size - data.length;
    return ByteString.copyFrom(zeros, 0, needed_zeros).concat(ByteString.copyFrom(data));
  }
}
 
Example 29
Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: Password.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Change a password read from Console.readPassword() into
 * its original bytes.
 *
 * @param pass a char[]
 * @return its byte[] format, similar to new String(pass).getBytes()
 */
private static byte[] convertToBytes(char[] pass) {
    if (enc == null) {
        synchronized (Password.class) {
            enc = sun.misc.SharedSecrets.getJavaIOAccess()
                    .charset()
                    .newEncoder()
                    .onMalformedInput(CodingErrorAction.REPLACE)
                    .onUnmappableCharacter(CodingErrorAction.REPLACE);
        }
    }
    byte[] ba = new byte[(int)(enc.maxBytesPerChar() * pass.length)];
    ByteBuffer bb = ByteBuffer.wrap(ba);
    synchronized (enc) {
        enc.reset().encode(CharBuffer.wrap(pass), bb, true);
    }
    if (bb.position() < ba.length) {
        ba[bb.position()] = '\n';
    }
    return ba;
}
 
Example 30
Project: bean-sdk-android   Author: PunchThrough   File: SketchHex.java    License: MIT License 6 votes vote down vote up
/**
 * Convert a list of Intel Hex {@link com.punchthrough.bean.sdk.internal.intelhex.Line} objects
 * to an array of the raw bytes they represent.
 *
 * @param lines The List of {@link com.punchthrough.bean.sdk.internal.intelhex.Line} objects
 * @return      An array of raw bytes represented by the
 *              {@link com.punchthrough.bean.sdk.internal.intelhex.Line} objects
 */
private static byte[] convertLinesToBytes(List<Line> lines) {
    List<Line> dataLines = new ArrayList<>();
    int byteCount = 0;
    for (Line line : lines) {
        if (line.getRecordType() == LineRecordType.DATA) {
            dataLines.add(line);
            byteCount += line.getByteCount();
        }
    }

    byte[] bytes = new byte[byteCount];
    int i = 0;
    for (Line line : dataLines) {
        for (byte b : line.getData()) {
            bytes[i] = b;
            i++;
        }
    }

    return bytes;
}
 
Example 31
Project: diozero   Author: mattjlewis   File: FirmataAdapter.java    License: MIT License 6 votes vote down vote up
static byte[] convertToBytes(int value) {
	int num_bytes;
	if (value < 128 || value >= 268435456) { // 2^7 or greater than max val (2^28)
		num_bytes = 1;
	} else if (value < 16384) { // 2^14
		num_bytes = 2;
	} else if (value < 2097152) { // 2^21
		num_bytes = 3;
	} else {
		num_bytes = 4;
	}
	byte[] bytes = new byte[num_bytes];
	for (int i = 0; i < num_bytes; i++) {
		bytes[i] = (byte) ((value >> (i * 7)) & 0x7f);
	}
	return bytes;
}
 
Example 32
Project: bytes-java   Author: patrickfav   File: BytesToConvertOtherTypesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void toDouble() {
    assertEquals(-6.659307728279082E225, Bytes.from(example_bytes_eight).toDouble(), 0.001);

    assertEquals(5.1E-322, Bytes.from(new byte[]{0, 0, 0, 0, 0, 0, 0}, example_bytes_one).toDouble(), 0.001);
    assertEquals(3.3433E-320, Bytes.from(new byte[]{0, 0, 0, 0, 0, 0}, example_bytes_two).toDouble(), 0.001);
    assertEquals(0, Bytes.from(new byte[8]).toDouble(), 0);

    try {
        Bytes.from(new byte[9]).toDouble();
        fail();
    } catch (IllegalArgumentException ignored) {
    }
    try {
        Bytes.from(new byte[7]).toDouble();
        fail();
    } catch (IllegalArgumentException ignored) {
    }
}
 
Example 33
Project: bytes-java   Author: patrickfav   File: BytesToConvertOtherTypesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void toInt() {
    assertEquals(591065872, Bytes.from(example_bytes_four).toInt());
    assertEquals(Bytes.from(new byte[]{0, 0, 0, 0}, example_bytes_four).toLong(), Bytes.from(example_bytes_four).toInt());

    System.out.println(Bytes.from(new byte[]{0, 0, 0x01, 0x02}).resize(4).encodeHex());
    System.out.println(Bytes.from(new byte[]{0x01, 0x02, 0x03, 0x04}).resize(4).encodeHex());

    assertEquals(6767, Bytes.from(new byte[]{(byte) 0, (byte) 0}, example_bytes_two).toInt());
    assertEquals(0, Bytes.from(new byte[4]).toInt());

    try {
        Bytes.from(new byte[5]).toInt();
        fail();
    } catch (IllegalArgumentException ignored) {
    }
    try {
        Bytes.from(new byte[3]).toInt();
        fail();
    } catch (IllegalArgumentException ignored) {
    }
}
 
Example 34
Project: android_9.0.0_r45   Author: lulululbj   File: BluetoothDevice.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check that a pin is valid and convert to byte array.
 *
 * Bluetooth pin's are 1 to 16 bytes of UTF-8 characters.
 *
 * @param pin pin as java String
 * @return the pin code as a UTF-8 byte array, or null if it is an invalid Bluetooth pin.
 * @hide
 */
public static byte[] convertPinToBytes(String pin) {
    if (pin == null) {
        return null;
    }
    byte[] pinBytes;
    try {
        pinBytes = pin.getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
        Log.e(TAG, "UTF-8 not supported?!?");  // this should not happen
        return null;
    }
    if (pinBytes.length <= 0 || pinBytes.length > 16) {
        return null;
    }
    return pinBytes;
}
 
Example 35
Project: feast   Author: feast-dev   File: FeatureSetJsonByteConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConvertFeatureSetsAsJsonStringBytes() throws InvalidProtocolBufferException {
  int nrOfFeatureSet = 1;
  int nrOfFeatures = 1;
  List<FeatureSetProto.FeatureSet> featureSets =
      IntStream.range(1, nrOfFeatureSet + 1)
          .mapToObj(i -> newFeatureSet(nrOfFeatures))
          .collect(Collectors.toList());

  String expectedOutputString =
      "{\"entities\":[{\"name\":\"entity\",\"valueType\":2}],"
          + "\"features\":[{\"name\":\"feature1\",\"valueType\":6}],"
          + "\"source\":{"
          + "\"type\":1,"
          + "\"kafkaSourceConfig\":{"
          + "\"bootstrapServers\":\"somebrokers:9092\","
          + "\"topic\":\"sometopic\"}}}";
  FeatureSetJsonByteConverter byteConverter = new FeatureSetJsonByteConverter();
  assertEquals(expectedOutputString, new String(byteConverter.toByte(featureSets)));
}
 
Example 36
Project: soltix   Author: eth-sri   File: BytesValue.java    License: Apache License 2.0 6 votes vote down vote up
public IntegerValue convertToIntegerType(ASTElementaryTypeName newType) throws Exception {
    // First construct unsigned integer type of same size and with the value
    String s = "";
    for (int i = 0; i < value.length; ++i) {
        s += String.format("%02x", value[i]);
    }
    BigInteger unsgnedInteger = new BigInteger(s, 16);

    ASTElementaryTypeName unsignedType = TypeContainer.getIntegerType(false, type.getBytes() * 8);
    IntegerValue unsignedIntegerValue = ValueContainer.getBigIntegerValue(unsignedType, unsgnedInteger);

    if (Type.isSameType(null, unsignedType, newType)) {
        return unsignedIntegerValue;
    } else {
        return unsignedIntegerValue.convertToIntegerType(newType);
    }
}
 
Example 37
Project: jdk8u-jdk   Author: frohoff   File: WDataTransferer.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
Example 38
Project: AndroidWallet   Author: Cocos-BCX   File: ConvertUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * bits转bytes
 *
 * @param bits 二进制
 * @return bytes
 */
public static byte[] bits2Bytes(String bits) {
    int lenMod = bits.length() % 8;
    int byteLen = bits.length() / 8;
    // 不是8的倍数前面补0
    if (lenMod != 0) {
        for (int i = lenMod; i < 8; i++) {
            bits = "0" + bits;
        }
        byteLen++;
    }
    byte[] bytes = new byte[byteLen];
    for (int i = 0; i < byteLen; ++i) {
        for (int j = 0; j < 8; ++j) {
            bytes[i] <<= 1;
            bytes[i] |= bits.charAt(i * 8 + j) - '0';
        }
    }
    return bytes;
}
 
Example 39
Project: consulo   Author: consulo   File: LoadTextUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static ConvertResult convertBytes(@Nonnull byte[] bytes, final int startOffset, int endOffset, @Nonnull Charset internalCharset) {
  assert startOffset >= 0 && startOffset <= endOffset && endOffset <= bytes.length : startOffset + "," + endOffset + ": " + bytes.length;
  if (internalCharset instanceof SevenBitCharset || internalCharset == CharsetToolkit.US_ASCII_CHARSET) {
    // optimisation: skip byte-to-char conversion for ascii chars
    return convertLineSeparatorsToSlashN(bytes, startOffset, endOffset);
  }

  ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, startOffset, endOffset - startOffset);

  CharBuffer charBuffer;
  try {
    charBuffer = internalCharset.decode(byteBuffer);
  }
  catch (Exception e) {
    // esoteric charsets can throw any kind of exception
    charBuffer = CharBuffer.wrap(ArrayUtilRt.EMPTY_CHAR_ARRAY);
  }
  return convertLineSeparatorsToSlashN(charBuffer);
}
 
Example 40
Project: dragonwell8_jdk   Author: alibaba   File: WDataTransferer.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
Example 41
Project: dragonwell8_jdk   Author: alibaba   File: Password.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Change a password read from Console.readPassword() into
 * its original bytes.
 *
 * @param pass a char[]
 * @return its byte[] format, similar to new String(pass).getBytes()
 */
private static byte[] convertToBytes(char[] pass) {
    if (enc == null) {
        synchronized (Password.class) {
            enc = sun.misc.SharedSecrets.getJavaIOAccess()
                    .charset()
                    .newEncoder()
                    .onMalformedInput(CodingErrorAction.REPLACE)
                    .onUnmappableCharacter(CodingErrorAction.REPLACE);
        }
    }
    byte[] ba = new byte[(int)(enc.maxBytesPerChar() * pass.length)];
    ByteBuffer bb = ByteBuffer.wrap(ba);
    synchronized (enc) {
        enc.reset().encode(CharBuffer.wrap(pass), bb, true);
    }
    if (bb.position() < ba.length) {
        ba[bb.position()] = '\n';
    }
    return ba;
}
 
Example 42
Project: jdk8u-jdk   Author: lambdalab-mirror   File: WDataTransferer.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
Example 43
Project: slick2d-maven   Author: nguillaumin   File: WaveData.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Convert the audio bytes into the stream
 * 
 * @param audio_bytes The audio byts
 * @param two_bytes_data True if we using double byte data
 * @return The byte bufer of data
 */
private static ByteBuffer convertAudioBytes(byte[] audio_bytes, boolean two_bytes_data) {
	ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
	dest.order(ByteOrder.nativeOrder());
	ByteBuffer src = ByteBuffer.wrap(audio_bytes);
	src.order(ByteOrder.LITTLE_ENDIAN);
	if (two_bytes_data) {
		ShortBuffer dest_short = dest.asShortBuffer();
		ShortBuffer src_short = src.asShortBuffer();
		while (src_short.hasRemaining())
			dest_short.put(src_short.get());
	} else {
		while (src.hasRemaining())
			dest.put(src.get());
	}
	dest.rewind();
	return dest;
}
 
Example 44
Project: jdk8u-dev-jdk   Author: frohoff   File: WDataTransferer.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
Example 45
Project: datacollector   Author: streamsets   File: TestMetricsEnabledWrapperStream.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertBytesToDisplayFormat() throws Exception {
  //Bytes
  Assert.assertEquals("1023 B", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1023d));
  Assert.assertEquals("512 B", MetricEnabledWrapperStream.convertBytesToDisplayFormat(512d));
  Assert.assertEquals("0 B", MetricEnabledWrapperStream.convertBytesToDisplayFormat(0d));

  //KB
  Assert.assertEquals("1 KB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1025d));
  Assert.assertEquals("1.5 KB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1540d));
  Assert.assertEquals("1.55 KB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1588d));
  Assert.assertEquals("1023.99 KB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1048570d));

  //MB
  Assert.assertEquals("1 MB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1048576d));
  Assert.assertEquals("100.98 MB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(105885205d));
  Assert.assertEquals("1024 MB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1073741810d));

  //GB
  Assert.assertEquals("1 GB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1073741824d));
  Assert.assertEquals("1024 GB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1099511627774d));

  //TB
  Assert.assertEquals("1 TB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1099511627776d));
  Assert.assertEquals("1025 TB", MetricEnabledWrapperStream.convertBytesToDisplayFormat(1126999418470400d));
}
 
Example 46
Project: BlogDemo   Author: FantasyLWX   File: ConvertUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Bytes to output stream.
 *
 * @param bytes The bytes.
 * @return output stream
 */
public static OutputStream bytesToOutputStream(byte[] bytes) {
    if (bytes == null || bytes.length <= 0) return null;
    ByteArrayOutputStream os = null;
    try {
        os = new ByteArrayOutputStream();
        os.write(bytes);
        return os;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 47
@Test
public void testConvertBytesMessageToAmqpMessageWithDataBody() throws Exception {
   byte[] expectedPayload = new byte[]{8, 16, 24, 32};
   ServerJMSBytesMessage outbound = createBytesMessage();
   outbound.writeBytes(expectedPayload);
   outbound.encode();

   AMQPMessage amqp = AMQPConverter.getInstance().fromCore(outbound.getInnerMessage(), null);

   assertNotNull(amqp.getBody());
   assertTrue(amqp.getBody() instanceof Data);
   assertTrue(((Data) amqp.getBody()).getValue() instanceof Binary);
   assertEquals(4, ((Data) amqp.getBody()).getValue().getLength());

   Binary amqpData = ((Data) amqp.getBody()).getValue();
   Binary inputData = new Binary(expectedPayload);

   assertTrue(inputData.equals(amqpData));
}
 
Example 48
Project: hivemq-community-edition   Author: hivemq   File: Strings.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>This method can be used to convert a long value into a human readable byte format</p>
 *
 * <p>1024 bytes = 1.00 KB</p>
 * <p>1024*1024 bytes = 1.00 MB</p>
 * <p>1024*1024*1024 bytes = 1.00 GB</p>
 * <p>1024*1024*1024*1024 bytes = 1.00 TB</p>
 *
 * @param bytes the long value to convert
 * @return the human readable converted String
 */
@VisibleForTesting
public static String convertBytes(final long bytes) {
    final long kbDivisor = 1024L;
    final long mbDivisor = kbDivisor * kbDivisor;
    final long gbDivisor = mbDivisor * kbDivisor;
    final long tbDivisor = gbDivisor * kbDivisor;

    if (bytes <= kbDivisor) {
        return bytes + " B";
    } else if (bytes <= mbDivisor) {
        final double kb = (double) bytes / kbDivisor;
        return String.format(Locale.US, "%.2f", kb) + " KB";
    } else if (bytes <= gbDivisor) {
        final double mb = (double) bytes / mbDivisor;
        return String.format(Locale.US, "%.2f", mb) + " MB";
    } else if (bytes <= tbDivisor) {
        final double gb = (double) bytes / gbDivisor;
        return String.format(Locale.US, "%.2f", gb) + " GB";
    } else {
        final double tb = (double) bytes / tbDivisor;
        return String.format(Locale.US, "%.2f", tb) + " TB";
    }
}
 
Example 49
Project: expper   Author: Raysmond   File: TestUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert an object to JSON byte array.
 *
 * @param object
 *            the object to convert
 * @return the JSON byte array
 * @throws IOException
 */
public static byte[] convertObjectToJsonBytes(Object object)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    mapper.registerModule(module);

    return mapper.writeValueAsBytes(object);
}
 
Example 50
Project: TencentKona-8   Author: Tencent   File: WDataTransferer.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
Example 51
Project: TencentKona-8   Author: Tencent   File: Password.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Change a password read from Console.readPassword() into
 * its original bytes.
 *
 * @param pass a char[]
 * @return its byte[] format, similar to new String(pass).getBytes()
 */
private static byte[] convertToBytes(char[] pass) {
    if (enc == null) {
        synchronized (Password.class) {
            enc = sun.misc.SharedSecrets.getJavaIOAccess()
                    .charset()
                    .newEncoder()
                    .onMalformedInput(CodingErrorAction.REPLACE)
                    .onUnmappableCharacter(CodingErrorAction.REPLACE);
        }
    }
    byte[] ba = new byte[(int)(enc.maxBytesPerChar() * pass.length)];
    ByteBuffer bb = ByteBuffer.wrap(ba);
    synchronized (enc) {
        enc.reset().encode(CharBuffer.wrap(pass), bb, true);
    }
    if (bb.position() < ba.length) {
        ba[bb.position()] = '\n';
    }
    return ba;
}
 
Example 52
Project: dhis2-core   Author: dhis2   File: TestUtils.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static byte[] convertObjectToJsonBytes( Object object ) throws IOException
{
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion( JsonInclude.Include.NON_NULL );
    objectMapper.configure( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false );
    objectMapper.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );
    objectMapper.configure( SerializationFeature.WRAP_EXCEPTIONS, true );
    objectMapper.setSerializationInclusion( JsonInclude.Include.NON_NULL );

    objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
    objectMapper.configure( DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true );
    objectMapper.configure( DeserializationFeature.WRAP_EXCEPTIONS, true );

    objectMapper.disable( MapperFeature.AUTO_DETECT_FIELDS );
    objectMapper.disable( MapperFeature.AUTO_DETECT_CREATORS );
    objectMapper.disable( MapperFeature.AUTO_DETECT_GETTERS );
    objectMapper.disable( MapperFeature.AUTO_DETECT_SETTERS );
    objectMapper.disable( MapperFeature.AUTO_DETECT_IS_GETTERS );

    return objectMapper.writeValueAsBytes( object );
}
 
Example 53
Project: JianshuApp   Author: imkarl   File: ConvertUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * bits转bytes
 *
 * @param bits 二进制
 * @return bytes
 */
public static byte[] bits2Bytes(String bits) {
    int lenMod = bits.length() % 8;
    int byteLen = bits.length() / 8;
    // 不是8的倍数前面补0
    if (lenMod != 0) {
        for (int i = lenMod; i < 8; i++) {
            bits = "0" + bits;
        }
        byteLen++;
    }
    byte[] bytes = new byte[byteLen];
    for (int i = 0; i < byteLen; ++i) {
        for (int j = 0; j < 8; ++j) {
            bytes[i] <<= 1;
            bytes[i] |= bits.charAt(i * 8 + j) - '0';
        }
    }
    return bytes;
}
 
Example 54
Project: ID-SDK   Author: 4iot-dev   File: MsgBytesConvertor.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] convertCreateIdentifierReqToBytes(CreateIdentifierRequest req) {
	// TODO Auto-generated method stub
	int bodyLen = Common.FOUR_SIZE + req.identifier.length + Common.FOUR_SIZE;
	if (req.values != null && req.values.length > 0) {
		for (int i = 0; i < req.values.length; i++)
			bodyLen += calcStorageSize(req.values[i]);
	}
	byte[] msg = new byte[bodyLen + Common.MESSAGE_HEADER_SIZE];
	int pos = writeHeader(req, msg, bodyLen);
	pos += writeByteArray(msg, pos, req.identifier, 0, req.identifier.length);
	if (req.values != null && req.values.length > 0) {
		pos += write4Bytes(msg, pos, req.values.length);
		for (int i = 0; i < req.values.length; i++) {
			pos += convertIdentifierValueToByte(msg, pos, req.values[i]);
		}
	} else {
		pos += write4Bytes(msg, pos, 0);
	}
	return msg;
}
 
Example 55
Project: ID-SDK   Author: 4iot-dev   File: MsgBytesConvertor.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] convertLoginReqToBytes(LoginRequest req) {
	int bodyLen = Common.FOUR_SIZE + req.identifier.length + Common.FOUR_SIZE
			+ ((req.requestedIndexes == null) ? 0 : req.requestedIndexes.length * Common.FOUR_SIZE)
			+ Common.FOUR_SIZE;
	if (req.requestedTypes != null) {
		for (int i = 0; i < req.requestedTypes.length; i++) {
			bodyLen += (req.requestedTypes[i].length + Common.FOUR_SIZE);
		}
	}
	byte[] msg = new byte[bodyLen + Common.MESSAGE_HEADER_SIZE];
	writeHeader(req, msg, bodyLen);
	int pos = Common.MESSAGE_HEADER_SIZE;
	pos += writeByteArray(msg, pos, req.identifier, 0, req.identifier.length);
	pos += writeIntArray(msg, pos, req.requestedIndexes);
	pos += writeByteArrayArray(msg, pos, req.requestedTypes);
	return msg;
}
 
Example 56
Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: WDataTransferer.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ByteArrayOutputStream convertFileListToBytes(ArrayList<String> fileList)
        throws IOException
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    if(fileList.isEmpty()) {
        //store empty unicode string (null terminator)
        bos.write(UNICODE_NULL_TERMINATOR);
    } else {
        for (int i = 0; i < fileList.size(); i++) {
            byte[] bytes = fileList.get(i).getBytes(getDefaultUnicodeEncoding());
            //store unicode string with null terminator
            bos.write(bytes, 0, bytes.length);
            bos.write(UNICODE_NULL_TERMINATOR);
        }
    }

    // According to MSDN the byte array have to be double NULL-terminated.
    // The array contains Unicode characters, so each NULL-terminator is
    // a pair of bytes

    bos.write(UNICODE_NULL_TERMINATOR);
    return bos;
}
 
Example 57
Project: java-technology-stack   Author: codeEngraver   File: MappingJackson2MessageConverter.java    License: MIT License 6 votes vote down vote up
/**
 * Convert a BytesMessage to a Java Object with the specified type.
 * @param message the input message
 * @param targetJavaType the target type
 * @return the message converted to an object
 * @throws JMSException if thrown by JMS
 * @throws IOException in case of I/O errors
 */
protected Object convertFromBytesMessage(BytesMessage message, JavaType targetJavaType)
		throws JMSException, IOException {

	String encoding = this.encoding;
	if (this.encodingPropertyName != null && message.propertyExists(this.encodingPropertyName)) {
		encoding = message.getStringProperty(this.encodingPropertyName);
	}
	byte[] bytes = new byte[(int) message.getBodyLength()];
	message.readBytes(bytes);
	try {
		String body = new String(bytes, encoding);
		return this.objectMapper.readValue(body, targetJavaType);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessageConversionException("Cannot convert bytes to String", ex);
	}
}
 
Example 58
Project: blade   Author: lets-blade   File: ConvertKit.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * bits转bytes
 *
 * @param bits 二进制
 * @return bytes
 */
public static byte[] bits2Bytes(String bits) {
    int lenMod  = bits.length() % 8;
    int byteLen = bits.length() / 8;
    // 不是8的倍数前面补0
    if (lenMod != 0) {
        for (int i = lenMod; i < 8; i++) {
            bits = "0" + bits;
        }
        byteLen++;
    }
    byte[] bytes = new byte[byteLen];
    for (int i = 0; i < byteLen; ++i) {
        for (int j = 0; j < 8; ++j) {
            bytes[i] <<= 1;
            bytes[i] |= bits.charAt(i * 8 + j) - '0';
        }
    }
    return bytes;
}
 
Example 59
Project: asciidoctorj   Author: asciidoctor   File: RubyOutputStreamWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private byte[] convertToBytes(IRubyObject arg) {
  if (arg instanceof RubyString) {
    return ((RubyString) arg).getBytes();
  } else if (arg instanceof RubyNumeric) {
    return arg.asString().getBytes();
  } else {
    throw new IllegalArgumentException("Don't know how to write a " + arg + " " + arg.getClass());
  }
}
 
Example 60
Project: bisq   Author: bisq-network   File: P2PDataStorage.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static Set<P2PDataStorage.ByteArray> convertBytesSetToByteArraySet(Set<byte[]> set) {
    return set != null ?
            set.stream()
                    .map(P2PDataStorage.ByteArray::new)
                    .collect(Collectors.toSet())
            : new HashSet<>();
}