Java Convert via ByteBuffer toBytes(String str, boolean wideChar)

Here you can find the source of toBytes(String str, boolean wideChar)

Description

to Bytes

License

Open Source License

Declaration

public static byte[] toBytes(String str, boolean wideChar) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * This program and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at 
 * http://www.eclipse.org/legal/cpl-v10.html
 * //from  w  ww.ja v a 2 s  .  c  o  m
 * Contributors:
 *     Peter Smith
 *******************************************************************************/

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    public static byte[] toBytes(String str, boolean wideChar) {
        int len = str.length() + 1;
        if (wideChar)
            len <<= 1;
        byte[] buf = new byte[len];
        ByteBuffer bb = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN);
        for (int i = 0; i < str.length(); i++) {
            if (wideChar)
                bb.putChar(str.charAt(i));
            else
                bb.put((byte) str.charAt(i));
        }
        if (wideChar)
            bb.putChar((char) 0);
        else
            bb.put((byte) 0);
        return buf;
    }
}

Related

  1. toBytes(InputStream input)
  2. toBytes(int value)
  3. toBytes(long l)
  4. toBytes(Number value)
  5. toBytes(Object obj)
  6. toBytes(String value)
  7. toBytes(UUID id)
  8. toBytesAsString(UUID uuid)
  9. toChars(byte[] bytes)