Java Byte Array Create toBytes(Object value)

Here you can find the source of toBytes(Object value)

Description

Converts a string to a bytes integer, interpreting 'b', 'kb', 'mb', 'gb' and 'tb' suffixes.

License

LGPL

Parameter

Parameter Description
value The value

Return

The bytes

Declaration

public static int toBytes(Object value) 

Method Source Code

//package com.java2s;
/**//from   w w w.ja v  a  2  s .  co  m
 * Copyright 2009-2016 Three Crickets LLC.
 * <p>
 * The contents of this file are subject to the terms of the LGPL version 3.0:
 * http://www.gnu.org/copyleft/lesser.html
 * <p>
 * Alternatively, you can obtain a royalty free commercial license with less
 * limitations, transferable or non-transferable, directly from Three Crickets
 * at http://threecrickets.com/
 */

public class Main {
    /**
     * Converts a string to a bytes integer, interpreting 'b', 'kb', 'mb', 'gb'
     * and 'tb' suffixes. Numbers are simply rounded to an integer.
     * <p>
     * Fractions can be used, and are rounded to the nearest byte, for example:
     * "1.5mb".
     * 
     * @param value
     *        The value
     * @return The bytes
     */
    public static int toBytes(Object value) {
        if (value == null)
            return 0;
        if (value instanceof Number)
            return ((Number) value).intValue();
        else {
            String s = value.toString();
            if (s.endsWith("kb"))
                return (int) (Float.parseFloat(s.substring(0,
                        s.length() - 2)) * 1024f);
            else if (s.endsWith("mb"))
                return (int) (Float.parseFloat(s.substring(0,
                        s.length() - 2)) * 1048576f);
            else if (s.endsWith("gb"))
                return (int) (Float.parseFloat(s.substring(0,
                        s.length() - 2)) * 1073741824f);
            else if (s.endsWith("tb"))
                return (int) (Float.parseFloat(s.substring(0,
                        s.length() - 2)) * 1099511627776f);
            else if (s.endsWith("b"))
                return (int) Float
                        .parseFloat(s.substring(0, s.length() - 1));
            else
                return (int) Float.parseFloat(s);
        }

    }
}

Related

  1. toBytes(long value)
  2. toBytes(long value)
  3. toBytes(long value, int numBytes)
  4. toBytes(long... values)
  5. toBytes(Object objValue)
  6. toBytes(short s)
  7. toBytes(short s)
  8. toBytes(short sVal, byte[] bytes, boolean bigEndian)
  9. toBytes(short value)