下面列出了怎么用java.nio.ByteOrder的API类实例代码及写法,或者点击链接到github查看源代码。
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int in_len = out_len * 8;
if (bytebuffer == null || bytebuffer.capacity() < in_len) {
bytebuffer = ByteBuffer.allocate(in_len).order(
ByteOrder.LITTLE_ENDIAN);
floatbuffer = bytebuffer.asDoubleBuffer();
}
bytebuffer.position(0);
floatbuffer.position(0);
bytebuffer.put(in_buff, in_offset, in_len);
if (double_buff == null
|| double_buff.length < out_len + out_offset)
double_buff = new double[out_len + out_offset];
floatbuffer.get(double_buff, out_offset, out_len);
int out_offset_end = out_offset + out_len;
for (int i = out_offset; i < out_offset_end; i++) {
out_buff[i] = (float) double_buff[i];
}
return out_buff;
}
public CubeRenderer()
{
cubeBuffer = ByteBuffer.allocateDirect(cube.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
cubeBuffer.put(cube).position(0);
indexBuffer = ByteBuffer.allocateDirect(indeces.length * 4).order(ByteOrder.nativeOrder()).asShortBuffer();
indexBuffer.put(indeces).position(0);
texBuffer = ByteBuffer.allocateDirect(tex.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
texBuffer.put(tex).position(0);
iProgId = loadProgram(strVShader, strFShader);
iPosition = GLES20.glGetAttribLocation(iProgId, "a_position");
iVPMatrix = GLES20.glGetUniformLocation(iProgId, "u_VPMatrix");
iTexLoc = GLES20.glGetUniformLocation(iProgId, "u_texId");
iTexCoords = GLES20.glGetAttribLocation(iProgId, "a_texCoords");
iTexId = createCubeTexture();
createVertexBuffers();
}
/**
* Convert the audio bytes into the stream
*
* @param format The audio format being decoded
* @param audio_bytes The audio byts
* @param two_bytes_data True if we using double byte data
* @return The byte bufer of data
*/
private static ByteBuffer convertAudioBytes(AudioFormat format, byte[] audio_bytes, boolean two_bytes_data) {
ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
dest.order(ByteOrder.nativeOrder());
ByteBuffer src = ByteBuffer.wrap(audio_bytes);
src.order(ByteOrder.BIG_ENDIAN);
if (two_bytes_data) {
ShortBuffer dest_short = dest.asShortBuffer();
ShortBuffer src_short = src.asShortBuffer();
while (src_short.hasRemaining())
dest_short.put(src_short.get());
} else {
while (src.hasRemaining()) {
byte b = src.get();
if (format.getEncoding() == Encoding.PCM_SIGNED) {
b = (byte) (b + 127);
}
dest.put(b);
}
}
dest.rewind();
return dest;
}
/**
* Completes the current frame, signaling that no further data is available to be passed to
* readBytes and that the client requires writeBytes to start returning data. isComplete() is
* guaranteed to return true after this call.
*/
void flush() throws GeneralSecurityException {
if (isComplete) {
return;
}
// Get the length of the complete frame.
int frameLength = buffer.position() + getFrameSuffixLength();
// Set the limit and move to the start.
buffer.flip();
// Advance the limit to allow a crypto suffix.
buffer.limit(buffer.limit() + getFrameSuffixLength());
// Write the data length and the message type.
int dataLength = frameLength - FRAME_LENGTH_HEADER_SIZE;
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(dataLength);
buffer.putInt(MESSAGE_TYPE);
// Move the position back to 0, the frame is ready.
buffer.position(0);
isComplete = true;
}
@Override
public void loadInMemoryStorage(
final byte[] buffer ,
final int start ,
final int length ,
final IMemoryAllocator allocator ,
final byte[] isNullArray ,
final int size ,
final boolean hasNull ,
final ByteOrder order ) throws IOException {
IReadSupporter wrapBuffer =
ByteBufferSupporterFactory.createReadSupporter( buffer , start , length , order );
for ( int i = 0 ; i < size ; i++ ) {
if ( ! hasNull || isNullArray[i] == 0 ) {
allocator.setLong(
i , NumberToBinaryUtils.getUnsignedShortToLong( wrapBuffer.getShort() ) + min );
} else {
allocator.setNull( i );
}
}
}
private static void testEncodeDecode(int size, ByteOrder order) {
byte[] bytes = new byte[size];
PlatformDependent.threadLocalRandom().nextBytes(bytes);
ByteBuf src = Unpooled.wrappedBuffer(bytes).order(order);
ByteBuf encoded = Base64.encode(src);
ByteBuf decoded = Base64.decode(encoded);
ByteBuf expectedBuf = Unpooled.wrappedBuffer(bytes);
try {
assertEquals(StringUtil.NEWLINE + "expected: " + ByteBufUtil.hexDump(expectedBuf) +
StringUtil.NEWLINE + "actual--: " + ByteBufUtil.hexDump(decoded), expectedBuf, decoded);
} finally {
src.release();
encoded.release();
decoded.release();
expectedBuf.release();
}
}
private Exchange(Builder builder) {
this.host = builder.host;
this.port = builder.port;
this.contextPath = builder.contextPath;
// Jetty uses big-endian buffers for receiving but converts them to byte[]
this.inboundRingBuffer = new RingBufferSupplier(incomingMessageConsumer, 1024,
ByteOrder.nativeOrder(), 64, Executors.defaultThreadFactory());
MessageProvider messageProvider = provider(builder.encoding);
encodingType = messageProvider.encodingType();
this.requestMessageFactory = messageProvider.getRequestMessageFactory();
MutableResponseMessageFactory responseMessageFactory =
messageProvider.getMutableResponseMessageFactory(outboundBufferSupplier);
this.matchEngine = new MatchEngine(responseMessageFactory);
this.sessions = new ServerSessions(new ServerSessionFactory(messageProvider,
sessionMessageConsumer, timer, executor, builder.heartbeatInterval));
Path outputPath = FileSystems.getDefault().getPath(builder.outputPath);
this.inboundLogWriter = new MessageLogWriter(outputPath.resolve("inbound.log"), false);
this.outboundLogWriter = new MessageLogWriter(outputPath.resolve("outbound.log"), false);
this.keyStorePath = builder.keyStorePath;
this.keyStorePassword = builder.keyStorePassword;
}
@Override
public void queueInput(ByteBuffer inputBuffer) {
Assertions.checkState(sonic != null);
if (inputBuffer.hasRemaining()) {
ShortBuffer shortBuffer = inputBuffer.asShortBuffer();
int inputSize = inputBuffer.remaining();
inputBytes += inputSize;
sonic.queueInput(shortBuffer);
inputBuffer.position(inputBuffer.position() + inputSize);
}
int outputSize = sonic.getFramesAvailable() * channelCount * 2;
if (outputSize > 0) {
if (buffer.capacity() < outputSize) {
buffer = ByteBuffer.allocateDirect(outputSize).order(ByteOrder.nativeOrder());
shortBuffer = buffer.asShortBuffer();
} else {
buffer.clear();
shortBuffer.clear();
}
sonic.getOutput(shortBuffer);
outputBytes += outputSize;
buffer.limit(outputSize);
outputBuffer = buffer;
}
}
private static long makeSeedForBiomeZoomer(long seed) throws MinecraftInterfaceException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
ByteBuffer buf = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
buf.putLong(seed);
byte[] bytes = digest.digest(buf.array());
long result = 0;
for (int i = 0; i < 8; i++) {
result |= (bytes[i] & 0xffL) << (i*8L);
}
return result;
} catch (NoSuchAlgorithmException e) {
throw new MinecraftInterfaceException("unable to hash seed", e);
}
}
private static ByteBuffer createByteBufferFile(int size) {
try {
if (tmpDir != null && logger.isLoggable(Level.INFO)) {
logger.log(Level.INFO, "tmpDir = {0}", tmpDir.getAbsoluteFile());
}
File tmpFile = File.createTempFile("pmd","tmp", tmpDir);
if (logger.isLoggable(Level.INFO)) {
logger.log(Level.INFO, "tmpFile = {0}", tmpFile.getAbsoluteFile());
}
RandomAccessFile os = new RandomAccessFile(tmpFile, "rw");
os.seek(size);
os.write(0);
FileChannel ch = os.getChannel();
MappedByteBuffer bb = ch.map(MapMode.READ_WRITE, 0, size);
os.close();
ch.close();
tmpFile.delete();
bb.order(ByteOrder.nativeOrder());
return bb;
} catch(IOException ex) {
throw new RuntimeException(ex);
}
}
public CoreParsedAdvertisement(byte[] rawAdData) {
this.rawAdData = rawAdData;
ByteBuffer byteBuffer = ByteBuffer.wrap(rawAdData).order(ByteOrder.LITTLE_ENDIAN);
try {
while (byteBuffer.hasRemaining()) {
int length = byteBuffer.get() & 0xFF;
if (length <= byteBuffer.remaining()) {
int dataType = byteBuffer.get() & 0xFF;
parseAdData(dataType, length - 1, byteBuffer);
}
}
} catch (Exception e) {
// Ignore exceptions; further data will not be parsed.
}
}
private void testMediumConsistentWithByteBuffer(boolean direct, boolean testBigEndian) {
for (int i = 0; i < JAVA_BYTEBUFFER_CONSISTENCY_ITERATIONS; ++i) {
ByteBuffer javaBuffer = direct ? ByteBuffer.allocateDirect(buffer.capacity())
: ByteBuffer.allocate(buffer.capacity());
if (!testBigEndian) {
javaBuffer = javaBuffer.order(ByteOrder.LITTLE_ENDIAN);
}
int expected = random.nextInt() & 0x00FFFFFF;
javaBuffer.putInt(expected);
final int bufferIndex = buffer.capacity() - 3;
if (testBigEndian) {
buffer.setMedium(bufferIndex, expected);
} else {
buffer.setMediumLE(bufferIndex, expected);
}
javaBuffer.flip();
int javaActual = javaBuffer.getInt();
assertEquals(expected, javaActual);
assertEquals(javaActual, testBigEndian ? buffer.getUnsignedMedium(bufferIndex)
: buffer.getUnsignedMediumLE(bufferIndex));
}
}
private void configureEGLPbufferSurfaces(Collection<EGLSurfaceHolder> surfaces) {
if (surfaces == null || surfaces.size() == 0) {
throw new IllegalStateException("No Surfaces were provided to draw to");
}
int maxLength = 0;
for (EGLSurfaceHolder holder : surfaces) {
int length = holder.width * holder.height;
// Find max surface size, ensure PBuffer can hold this many pixels
maxLength = (length > maxLength) ? length : maxLength;
int[] surfaceAttribs = {
EGL14.EGL_WIDTH, holder.width,
EGL14.EGL_HEIGHT, holder.height,
EGL14.EGL_NONE
};
holder.eglSurface =
EGL14.eglCreatePbufferSurface(mEGLDisplay, mConfigs, surfaceAttribs, 0);
checkEglError("eglCreatePbufferSurface");
}
mPBufferPixels = ByteBuffer.allocateDirect(maxLength * PBUFFER_PIXEL_BYTES)
.order(ByteOrder.nativeOrder());
}
/**
* Test an compact large header
*
* @throws CTFException
* if {@link BitBuffer} is null
*/
@Test
public void testLargeCompact() throws CTFException {
ByteBuffer buffer = ByteBuffer.allocate(16);
buffer.putShort((short) ID);
buffer.putInt(TIMESTAMP);
byte[] validLarge1 = buffer.array();
EventHeaderLargeDeclaration decl = EventHeaderLargeDeclaration.getEventHeader(ByteOrder.BIG_ENDIAN);
final ByteBuffer input = ByteBuffer.wrap(validLarge1);
assertNotNull(input);
EventHeaderDefinition def = decl.createDefinition(null, "bla", new BitBuffer(input));
assertNotNull(def);
assertEquals(ID, def.getId());
assertEquals(TIMESTAMP, def.getTimestamp());
assertEquals(ID, ((IntegerDefinition) def.getDefinition("id")).getValue());
assertEquals(TIMESTAMP, ((IntegerDefinition) def.getDefinition("timestamp")).getValue());
}
/**
* Creates a new DataChunk at the current position of the
* ImageOutputStream.
*
* @param chunkType The chunkType of the chunk.
*/
public FixedSizeDataChunk(int chunkType, long fixedSize) throws IOException {
super(chunkType);
this.fixedSize = fixedSize;
out.setByteOrder(ByteOrder.BIG_ENDIAN);
out.writeInt(chunkType);
out.setByteOrder(ByteOrder.LITTLE_ENDIAN);
out.writeInt((int) fixedSize);
// Fill fixed size with nulls
byte[] buf = new byte[(int) Math.min(512, fixedSize)];
long written = 0;
while (written < fixedSize) {
out.write(buf, 0, (int) Math.min(buf.length, fixedSize - written));
written += Math.min(buf.length, fixedSize - written);
}
if (fixedSize % 2 == 1) {
out.writeByte(0); // write pad byte
}
seekToStartOfData();
}
private void setColors(int[] faceColors) {
colors = new float[options * 4 * faceColors.length];
int wOffset = 0;
for (int faceColor : faceColors) {
float[] color = hexToRGBA(faceColor);
for(int j = 0; j < 4; j++) {
colors[wOffset++] = color[0];
colors[wOffset++] = color[1];
colors[wOffset++] = color[2];
colors[wOffset++] = color[3];
}
}
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * (Float.SIZE / 8));
cbb.order(ByteOrder.nativeOrder());
colorBuffer = cbb.asFloatBuffer();
colorBuffer.put(colors);
colorBuffer.position(0);
}
private static long getNumberOfClusters(final String filePath, final InputStream inputStream) {
final byte[] header = new byte[HEADER_SIZE];
try {
final int headerBytesRead = inputStream.read(header);
if (headerBytesRead != HEADER_SIZE) {
throw new PicardException("Malformed file, expected header of size " + HEADER_SIZE + " but received " + headerBytesRead);
}
} catch (final IOException ioe) {
throw new PicardException("Unable to read header for file (" + filePath + ")", ioe);
}
final ByteBuffer headerBuf = ByteBuffer.wrap(header);
headerBuf.order(ByteOrder.LITTLE_ENDIAN);
return UnsignedTypeUtil.uIntToLong(headerBuf.getInt());
}
@Test
public void testBigEndian() throws IOException {
String magic = "0 befloat >86400000000000 match";
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putFloat(Float.parseFloat("87200000000000"));
bb.flip();
byte[] bytes = bb.array();
testOutput(magic, bytes, "match");
bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putFloat(Float.parseFloat("8.2e+13"));
bb.flip();
bytes = bb.array();
testOutput(magic, bytes, null);
}
public double getDouble(final int index, final ByteOrder byteOrder)
{
boundsCheck(index, SIZE_OF_DOUBLE);
if (NATIVE_BYTE_ORDER != byteOrder)
{
final long bits = UNSAFE.getLong(byteArray, addressOffset + index);
return Double.longBitsToDouble(Long.reverseBytes(bits));
}
else
{
return UNSAFE.getDouble(byteArray, addressOffset + index);
}
}
/**
* Make deep copy from a StructureData to a ArrayStructureBB whose data is contained in a ByteBuffer
* @param sdata original ArrayStructure
* @param sm the StructureData members. a reference is kept to this object
* @param bo Byte Order of the ByteBuffer
* @return ArrayStructureBB with all data self contained
*/
static public ArrayStructureBB copyToArrayBB(StructureData sdata, StructureMembers sm, ByteOrder bo) {
int size = sm.getStructureSize();
ByteBuffer bb = ByteBuffer.allocate(size); // default is big endian
bb.order(bo);
ArrayStructureBB abb = new ArrayStructureBB(sm, new int[]{1}, bb, 0);
ArrayStructureBB.setOffsets(sm);
copyToArrayBB(sdata, abb);
return abb;
}
@Override
public void create( final List<byte[]> objList , final byte[] buffer , final int start , final int length , final ByteOrder order ) throws IOException{
IWriteSupporter wrapBuffer = ByteBufferSupporterFactory.createWriteSupporter( buffer , start , length , order );
for( byte[] obj : objList ){
wrapBuffer.putByte( (byte)obj.length );
}
}
private void update() {
float cos = (float) Math.cos(rotationAngle);
float sin = (float) Math.sin(rotationAngle);
float matrix[] = {
cos, sin, 0, 0,
-sin, cos, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
ByteBuffer buffer = uniformBuffer.getContents();
buffer.order(ByteOrder.nativeOrder());
buffer.asFloatBuffer().put(matrix);
rotationAngle += 0.01;
}
@Test
public void testWriteDataWithNull() throws ImageWriteException {
final FieldTypeByte fieldTypeByte = FieldType.UNDEFINED;
final ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
Assertions.assertThrows(ImageWriteException.class, () -> {
fieldTypeByte.writeData( null, byteOrder);
});
}
public void writeShort(int v) throws IOException {
if (byteOrder == ByteOrder.BIG_ENDIAN) {
byteBuf[0] = (byte)(v >>> 8);
byteBuf[1] = (byte)(v >>> 0);
} else {
byteBuf[0] = (byte)(v >>> 0);
byteBuf[1] = (byte)(v >>> 8);
}
write(byteBuf, 0, 2);
}
private void saveMesh(NavMesh mesh, String filePostfix) throws IOException {
// Set the flag to RecastDemo work properly
for (int i = 0; i < mesh.getTileCount(); i++) {
for (Poly p : mesh.getTile(i).data.polys) {
p.flags = 1;
}
}
// Save the mesh as recast file,
MeshSetWriter writer = new MeshSetWriter();
FileOutputStream os = new FileOutputStream(String.format("all_tiles_navmesh_%s.bin", filePostfix));
writer.write(os, mesh, ByteOrder.LITTLE_ENDIAN, true);
os.close();
}
public ByteBuffer encodeWindowUpdateFrame(int streamId, int deltaWindowSize) {
byte flags = 0;
int length = 8;
ByteBuffer frame = ByteBuffer.allocateDirect(SPDY_HEADER_SIZE + length).order(ByteOrder.BIG_ENDIAN);
writeControlFrameHeader(frame, SPDY_WINDOW_UPDATE_FRAME, flags, length);
frame.putInt(streamId);
frame.putInt(deltaWindowSize);
frame.flip();
return frame;
}
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule capsule = im.getCapsule(this);
numVertices = capsule.readInt("numVertices", 0);
numTriangles = capsule.readInt("numTriangles", 0);
vertexStride = capsule.readInt("vertexStride", 0);
triangleIndexStride = capsule.readInt("triangleIndexStride", 0);
triangleIndexBase = ByteBuffer.wrap(capsule.readByteArray("triangleIndexBase", new byte[0]));
vertexBase = ByteBuffer.wrap(capsule.readByteArray("vertexBase", new byte[0])).order(ByteOrder.nativeOrder());
createShape();
}
public long readLong() throws IOException {
// REMIND: Once 6277756 is fixed, we should do a bulk read of all 8
// bytes here as we do in readShort() and readInt() for even better
// performance (see 6347575 for details).
int i1 = readInt();
int i2 = readInt();
if (byteOrder == ByteOrder.BIG_ENDIAN) {
return ((long)i1 << 32) + (i2 & 0xFFFFFFFFL);
} else {
return ((long)i2 << 32) + (i1 & 0xFFFFFFFFL);
}
}
@Override
protected long _getLong(int index) {
Component c = findComponent(index);
if (index + 8 <= c.endOffset) {
return c.buf.getLong(index - c.offset);
} else if (order() == ByteOrder.BIG_ENDIAN) {
return (_getInt(index) & 0xffffffffL) << 32 | _getInt(index + 4) & 0xffffffffL;
} else {
return _getInt(index) & 0xFFFFFFFFL | (_getInt(index + 4) & 0xFFFFFFFFL) << 32;
}
}
public CameraGLRendererBase(CameraGLSurfaceView view) {
mView = view;
int bytes = vertices.length * Float.SIZE / Byte.SIZE;
vert = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer();
texOES = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer();
tex2D = ByteBuffer.allocateDirect(bytes).order(ByteOrder.nativeOrder()).asFloatBuffer();
vert.put(vertices).position(0);
texOES.put(texCoordOES).position(0);
tex2D.put(texCoord2D).position(0);
}