Java Encode encodeVarUInt32(int unsignedValue, OutputStream outputStream)

Here you can find the source of encodeVarUInt32(int unsignedValue, OutputStream outputStream)

Description

Encodes an unsigned uint32 value (represented as a signed int32 value) into a stream.

License

Open Source License

Parameter

Parameter Description
unsignedValue the value to encode, interpreted as unsigned
outputStream the output stream

Return

the number of bytes written to the stream (1-5)

Declaration

static int encodeVarUInt32(int unsignedValue, OutputStream outputStream) throws IOException 

Method Source Code


//package com.java2s;
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

import java.io.IOException;

import java.io.OutputStream;

public class Main {
    /**//from ww  w.  ja  va  2  s. c o m
     * Encodes an unsigned uint32 value (represented as a signed int32 value) into a stream.
     * The sign bit of the value is re-interpreted as the high order bit for encoding purposes.
     *
     * @param unsignedValue the value to encode, interpreted as unsigned
     * @param outputStream  the output stream
     * @return the number of bytes written to the stream (1-5)
     */
    static int encodeVarUInt32(int unsignedValue, OutputStream outputStream) throws IOException {
        int length = 1;

        // byte 0 (needs a special case to test for negative)
        if (unsignedValue >= 0x80 || unsignedValue < 0) {
            outputStream.write((byte) (unsignedValue | 0x80));
            unsignedValue >>>= 7;
            length = 2;

            // byte 1
            if (unsignedValue >= 0x80) {
                outputStream.write((byte) (unsignedValue | 0x80));
                unsignedValue >>>= 7;
                length = 3;

                // byte 2
                if (unsignedValue >= 0x80) {
                    outputStream.write((byte) (unsignedValue | 0x80));
                    unsignedValue >>>= 7;
                    length = 4;

                    // byte 3
                    if (unsignedValue >= 0x80) {
                        outputStream.write((byte) (unsignedValue | 0x80));
                        unsignedValue >>>= 7;
                        length = 5;
                    }
                }
            }
        }

        // last byte
        outputStream.write((byte) unsignedValue);

        return length;
    }
}

Related

  1. encodeUint(OutputStream out, final long value)
  2. encodeUInt32(int value, OutputStream out)
  3. encodeUnknownString(String in, OutputStream os)
  4. encodeUTCTime(long time, OutputStream os)
  5. encodeUtf8AsBase64(String data)
  6. encodeVarUInt64(long unsignedValue, OutputStream outputStream)
  7. encodeWikiTag(String s)
  8. encodeXML(String input)
  9. encodeXMLString(String aString, PrintWriter aWriter)