Conversion between a numeric type and a byte array

Source: Internet
Author: User

How do we choose to use a string or a number above? Explains the benefits of using numeric types, so the question is, how do you convert between numeric types and byte arrays?

Let's take a look at the conversion between a single numeric type and a byte array, as an example of an integer type:

public static byte[] Inttobytes (int x) {Bytebuffer Intbuffer = bytebuffer.allocate (integer.bytes);    Intbuffer.putint (0, X); return Intbuffer.array ();} public static int bytestoint (byte[] bytes) {return bytestoint (bytes, 0, bytes.length);} public static int bytestoint (byte[] bytes, int offset, int length) {Bytebuffer Intbuffer = bytebuffer.allocate (Integer .    BYTES);    Intbuffer.put (bytes, offset, length);    Intbuffer.flip (); return Intbuffer.getint ();}

Let's look at the conversions between multiple numeric types and byte arrays, with the example of converting between a long and a byte array:

Public static byte[] longsettobytes (Collection<long> ids) {     Int len = ids.size () *long.bytes;    bytebuffer bytebuffer =  Bytebuffer.allocate (len);     int start = 0;    for (Long  id : ids) {        bytebuffer.putlong (start, id);         start += Long.BYTES;    }     return bytebuffer.array ();} Public static set<long> bytestolongset (byte[] bytes) {    return  bytestolongset (bytes, 0, bytes.length);} Public static set<long> bytestolongset (Byte[] bytes, int offset, int  length) {    set<long> ids = new hashset<> ();     byteBuffer bytebuffer = bytebuffer.allocate (length);     bytebuffer.put (Bytes,  offset, length);     bytebuffer.flip ();     int count  = length/long.bytes;    for (int i=0; i<count; i++)  {         ids.add (Bytebuffer.getlong ());    }     return ids;}

Since Bytebuffer supports 5 numeric types, we provide complete support for conversions between numeric types and byte arrays, as shown in:

Conversion between a numeric type and a byte array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.