Conversion of Byte, int in "Goto" Java

Source: Internet
Author: User
Tags goto

Original URL: http://freewind886.blog.163.com/blog/static/661924642011810236100/

Recently in doing some coding and decoding related things, but also encountered the conversion of byte and int, looking at those about anti-code, the complement of instructions still headache, or write down some practical methods.
byte, int
Coercion type conversions can be used directly: byte B = (byte) aInt;
This operation is to intercept the lowest byte in int directly, and if int is greater than 255, the value becomes unrecognizable.
For an int obtained by Inputstream.read (), this method can be used to restore the value.

byte-int
There are two cases where a requirement to keep the value constant, such as a numerical calculation, can be cast with a forced type: int i = (int) abyte;
The other is to keep each bit in the lowest byte unchanged, 3 high bytes are all filled with 0, for example, to encode and decode operations,
You need to take a bitwise operation: int i = b & 0xFF;

int Inputstream.read ()
The function returns an int type, ranging from 0 to 255, and returns-1 if the end of the stream is reached. From the source of the Bytearrayinputstream, you can see how to go from byte to int
public synchronized int read () {
Return (POS < count)? (buf[pos++] & 0xff):-1;
}

int <-> byte[]
Code Transfer from:java int and byte conversions
public static byte[] Tobytearray (int iSource, int iarraylen) {
byte[] Blocalarr = new Byte[iarraylen];
for (int i = 0; (I < 4) && (I < iarraylen); i++) {
Blocalarr[i] = (byte) (ISource >> 8 * I & 0xFF);
}
return Blocalarr;
}

Converts a byte array Brefarr to an integer, and the lower byte array is the low byte bit of the integer type
public static int ToInt (byte[] brefarr) {
int ioutcome = 0;
BYTE bloop;

for (int i = 0; i < brefarr.length; i++) {
Bloop = Brefarr[i];
Ioutcome + = (bloop & 0xFF) << (8 * i);
}
return ioutcome;
}

Conversion of Byte, int in "Goto" Java

Related Article

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.