Java Convert via ByteBuffer stringToLong(String offsetString)

Here you can find the source of stringToLong(String offsetString)

Description

string To Long

License

Apache License

Declaration

public static long stringToLong(String offsetString) 

Method Source Code

//package com.java2s;
/*/*from   w  ww.  j  a  va 2  s  .  c o  m*/
 * Copyright (c) 2016 Red Hat, Inc., Rob Stryker, and Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    public static long stringToLong(String offsetString) {
        if (offsetString.charAt(0) == '0') {
            if (offsetString.length() > 1 && (offsetString.charAt(1) == 'x' || offsetString.charAt(1) == 'X')) {
                String ss = offsetString.substring(2);
                try {
                    return Long.parseLong(ss, 16);
                } catch (NumberFormatException nfe) {
                    // It's probably out of bounds, if it's a quad, so let's 
                    // try hex2bytes and get a long from that
                    byte[] bytes = hex2Bytes(ss);
                    ByteBuffer bb = ByteBuffer.allocate(8).wrap(bytes).order(ByteOrder.BIG_ENDIAN);
                    long l = bb.getLong();
                    return l;
                }
            }
            return Long.parseLong(offsetString, 8);
        }
        return Long.parseLong(offsetString);
    }

    public static byte[] hex2Bytes(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}

Related

  1. stringsToBinary(final String strings[])
  2. stringToBytes(final String inString)
  3. stringToBytes(String str)
  4. StringToData(String conv, boolean isRe, int number)
  5. stringToIpAddress(String s)
  6. stringToLongUnknownLength(String str, int startIndex)
  7. to32BitsLongArray(byte[] data, boolean bigEndian)
  8. toArray(final byte[] byteArray, final int sizeLimit)
  9. toArray(int value)