>>> data = (0x87,0x20,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22)
    >>> bytes2codeline(data)
    'PRINT "HELLO WORLD!"'
171392
def bytes2codeline(raw_bytes):
    
    code_line = ""
    func_token = False
    for byte_no in raw_bytes:
        if byte_no == 0xff: # Next byte is a function token
            func_token = True
            continue
        elif func_token == True:
            func_token = False
            try:
                character = FUNCTION_TOKEN[byte_no]
            except KeyError, err:
                print "Error: BASIC function torken for '%s' not found!" % hex(byte_no)
                character = chr(byte_no)
        elif byte_no in BASIC_TOKENS:
            try:
                character = BASIC_TOKENS[byte_no]
            except KeyError, err:
                print "Error: BASIC torken for '%s' not found!" % hex(byte_no)
                character = chr(byte_no)
        else:
            character = chr(byte_no)
#         print byte_no, repr(character)
        code_line += character
    return code_line
190210
def chunker(data, raise_exception=False):
    
    instructions = []
    data = bytes(data)
    while True:
        if len(data) == 0: break
        try:
            opcode = match_opcode(data)
        except:
            msg = 'unknown opcode starting with {}...)'.format(hex_format(data[0:4]))
            if raise_exception:
                raise ValueError(msg)
            else:
                logger.warning(msg)
                data = data[1:]
                continue
        opcode_def = OPCODES[opcode]
        num_bytes = len(opcode)
        if opcode_def[1] > 0: num_bytes += opcode_def[1]
        if 'raster' in opcode_def[0]:
            num_bytes += data[2] + 2
        #payload = data[len(opcode):num_bytes]
        instructions.append(data[:num_bytes])
        data = data[num_bytes:]
    return instructions
875959
def write_hex(fout, buf, offset, width=16):
    

    skipped_zeroes = 0
    for i, chunk in enumerate(chunk_iter(buf, width)):
        # zero skipping
        if chunk == (b"\x00" * width):
            skipped_zeroes += 1
            continue
        elif skipped_zeroes != 0:
            fout.write("  -- skipped zeroes: {}\n".format(skipped_zeroes))
            skipped_zeroes = 0

        # starting address of the current line
        fout.write("{:016x}  ".format(i * width + offset))

        # bytes column
        column = "  ".join([" ".join(["{:02x}".format(c) for c in subchunk])
                            for subchunk in chunk_iter(chunk, 8)])
        w = width * 2 + (width - 1) + ((width // 8) - 1)
        if len(column) != w:
            column += " " * (w - len(column))
        fout.write(column)

        # ASCII character column
        fout.write("  |")
        for c in chunk:
            if c in PRINTABLE_CHARS:
                fout.write(chr(c))
            else:
                fout.write(".")
        if len(chunk) < width:
            fout.write(" " * (width - len(chunk)))
        fout.write("|")

        fout.write("\n")
1053937
function(data) {

    var _mode = QRMode.MODE_8BIT_BYTE;
    var _data = data;
    var _parsedData = [];

    var _this = {};


    // Added to support UTF-8 Characters
    for (var i = 0, l = _data.length; i < l; i++) {
	var byteArray = [];
	var code = _data.charCodeAt(i);

	if (code > 0x10000) {
	    byteArray[0] = 0xF0 | ((code & 0x1C0000) >>> 18);
	    byteArray[1] = 0x80 | ((code & 0x3F000) >>> 12);
	    byteArray[2] = 0x80 | ((code & 0xFC0) >>> 6);
	    byteArray[3] = 0x80 | (code & 0x3F);
	} else if (code > 0x800) {
	    byteArray[0] = 0xE0 | ((code & 0xF000) >>> 12);
	    byteArray[1] = 0x80 | ((code & 0xFC0) >>> 6);
	    byteArray[2] = 0x80 | (code & 0x3F);
	} else if (code > 0x80) {
	    byteArray[0] = 0xC0 | ((code & 0x7C0) >>> 6);
	    byteArray[1] = 0x80 | (code & 0x3F);
	} else {
	    byteArray[0] = code;
	}

        // Fix Unicode corruption bug
        _parsedData.push(byteArray);
    }

    _parsedData = Array.prototype.concat.apply([], _parsedData);

    if (_parsedData.length != _data.length) {
	_parsedData.unshift(191);
	_parsedData.unshift(187);
	_parsedData.unshift(239);
    }

    var _bytes = _parsedData;

    _this.getMode = function() {
	return _mode;
    };

    _this.getLength = function(buffer) {
	return _bytes.length;
    };

    _this.write = function(buffer) {
	for (var i = 0; i < _bytes.length; i += 1) {
	    buffer.put(_bytes[i], 8);
	}
    };

    return _this;
}
433484
async def _pixy_data(self, data):
        
        if len(self.digital_pins) < PrivateConstants.PIN_PIXY_MOSI:
            # Pixy data sent before board finished pin discovery.
            # print("Pixy data sent before board finished pin discovery.")
            return

        # strip off sysex start and end
        data = data[1:-1]
        num_blocks = data[0]  # First byte is the number of blocks.
        # Prepare the new blocks list and then used it to overwrite the pixy_blocks.
        blocks = []
        # noinspection PyDictCreation
        for i in range(num_blocks):
            block = {}
            block["signature"] = int((data[i * 12 + 2] << 7) + data[i * 12 + 1])
            block["x"] = int((data[i * 12 + 4] << 7) + data[i * 12 + 3])
            block["y"] = int((data[i * 12 + 6] << 7) + data[i * 12 + 5])
            block["width"] = int((data[i * 12 + 8] << 7) + data[i * 12 + 7])
            block["height"] = int((data[i * 12 + 10] << 7) + data[i * 12 + 9])
            block["angle"] = int((data[i * 12 + 12] << 7) + data[i * 12 + 11])
            blocks.append(block)
        self.pixy_blocks = blocks
        if self.digital_pins[PrivateConstants.PIN_PIXY_MOSI].cb:
            if self.digital_pins[PrivateConstants.PIN_PIXY_MOSI].cb_type:
                await self.digital_pins[PrivateConstants.PIN_PIXY_MOSI].cb(blocks)
            else:
                loop = self.loop
                loop.call_soon(self.digital_pins[PrivateConstants.PIN_PIXY_MOSI].cb, blocks)
141611
def _string_to_byte_list(self, data):
        
        bytes_length = 16

        m = self.digest()
        m.update(str.encode(data))
        hex_digest = m.hexdigest()

        return list(int(hex_digest[num * 2:num * 2 + 2], bytes_length)
                    for num in range(bytes_length))
250168
def modutf7_decode(data: bytes) -> str:
    
    parts = []
    is_usascii = True
    buf = memoryview(data)
    while buf:
        byte = buf[0]
        if is_usascii:
            if buf[0:2] == b'&-':
                parts.append('&')
                buf = buf[2:]
            elif byte == 0x26:
                is_usascii = False
                buf = buf[1:]
            else:
                parts.append(chr(byte))
                buf = buf[1:]
        else:
            for i, byte in enumerate(buf):
                if byte == 0x2d:
                    to_decode = buf[:i].tobytes()
                    decoded = _modified_b64decode(to_decode)
                    parts.append(decoded)
                    buf = buf[i + 1:]
                    is_usascii = True
                    break
    if not is_usascii:
        to_decode = buf.tobytes()
        decoded = _modified_b64decode(to_decode)
        parts.append(decoded)
    return ''.join(parts)
925919
def tohexstring(self):
        
        val = self.tostring()
        st = "{0:0x}".format(int(val, 2))
        return st.zfill(len(self.bitmap)*2)
655891
def line_print(self):
        
        inv_types = {v: k for k, v in defines.Types.items()}

        if self._code is None:
            self._code = defines.Codes.EMPTY.number

        msg = "From {source}, To {destination}, {type}-{mid}, {code}-{token}, ["\
            .format(source=self._source, destination=self._destination, type=inv_types[self._type], mid=self._mid,
                    code=defines.Codes.LIST[self._code].name, token=self._token)
        for opt in self._options:
            msg += "{name}: {value}, ".format(name=opt.name, value=opt.value)
        msg += "]"
        if self.payload is not None:
            if isinstance(self.payload, dict):
                tmp = list(self.payload.values())[0][0:20]
            else:
                tmp = self.payload[0:20]
            msg += " {payload}...{length} bytes".format(payload=tmp, length=len(self.payload))
        else:
            msg += " No payload"
        return msg
754101
def decodeUcs2(byteIter, numBytes):
    
    userData = []
    i = 0
    try:
        while i < numBytes:
            userData.append(unichr((next(byteIter) << 8) | next(byteIter)))
            i += 2
    except StopIteration:
        # Not enough bytes in iterator to reach numBytes; return what we have
        pass
    return ''.join(userData)
963881
def print_block_bit_list(block_bit_list, display_block_count=8, no_repr=False):
    
    def print_line(no, line, line_info):
        print "%4s - %s" % (no, line)
        if no_repr:
            return

        line = []
        for codepoint in line_info:
            r = repr(chr(codepoint))
            if "\\x" in r: # FIXME
                txt = "%s" % hex(codepoint)
            else:
                txt = "%s %s" % (hex(codepoint), r)
            txt = txt.center(8)
            line.append(txt)

        print "       %s" % " ".join(line)


    in_line_count = 0

    line = ""
    line_info = []
    for no, bits in enumerate(block_bit_list, 1):
        line += "%s " % "".join([str(c) for c in bits])

        codepoint = bits2codepoint(bits)
        line_info.append(codepoint)

        in_line_count += 1
        if in_line_count >= display_block_count:
            in_line_count = 0
            print_line(no, line, line_info)
            line_info = []
            line = ""
    if line:
        print_line(no, line, line_info)

    if in_line_count > 0:
        print
1029239
private static String toHexString(byte[] bytes) {
        if (bytes.length == 0) {
            return "(empty)";
        }

        StringBuilder sb = new StringBuilder(bytes.length * 3 - 1);
        boolean isInitial = true;
        for (byte b : bytes) {
            if (isInitial) {
                isInitial = false;
            } else {
                sb.append(':');
            }

            int k = b & 0xFF;
            sb.append(HEXES[k >>> 4]);
            sb.append(HEXES[k & 0xF]);
        }

        return sb.toString();
    }
74366
def encode_bytes(self):
        
        with io.StringIO() as buf:
            for char in self.data:
                if not isinstance(char, int):
                    buf.write('{{0:0{0}b}}'.format(8).format(ord(char)))
                else:
                    buf.write('{{0:0{0}b}}'.format(8).format(char))
            return buf.getvalue()
1140271
static public void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Supply a Base32-encoded argument.");
            return;
        }
        System.out.println(" Original: " + args[0]);
        byte[] decoded = Base32.decode(args[0]);
        System.out.print("      Hex: ");
        for (int i = 0; i < decoded.length; i++) {
            int b = decoded[i];
            if (b < 0) {
                b += 256;
            }
            System.out.print((Integer.toHexString(b + 256)).substring(1));
        }
        System.out.println();
        System.out.println("Reencoded: " + Base32.encode(decoded));
    }
1164058
def hexdump( src, length=16, sep='.', start = 0):
	'''
	
	'''
	result = [];

	# Python3 support
	try:
		xrange(0,1);
	except NameError:
		xrange = range;

	for i in xrange(0, len(src), length):
		subSrc = src[i:i+length];
		hexa = '';
		isMiddle = False;
		for h in xrange(0,len(subSrc)):
			if h == length/2:
				hexa += ' ';
			h = subSrc[h];
			if not isinstance(h, int):
				h = ord(h);
			h = hex(h).replace('0x','');
			if len(h) == 1:
				h = '0'+h;
			hexa += h+' ';
		hexa = hexa.strip(' ');
		text = '';
		for c in subSrc:
			if not isinstance(c, int):
				c = ord(c);
			if 0x20 <= c < 0x7F:
				text += chr(c);
			else:
				text += sep;
		if start == 0:
			result.append(('%08x:  %-'+str(length*(2+1)+1)+'s  |%s|') % (i, hexa, text));
		else:
			result.append(('%08x(+%04x):  %-'+str(length*(2+1)+1)+'s  |%s|') % (start+i, i, hexa, text));
	return '\n'.join(result);
1268839
def bytes_to_c_string(data):
    
    rows = chunked_join(data, 20, 2, '"\n    "', '', r'\x' + X)
    logging.debug(_('Returning rows: %s'), rows)
    return '"{}";'.format(rows)
114168
static private void encodeBytes(byte previous, byte current, int byteIndex, StringBuilder output) {
        int chunk;
        int offset = byteIndex % 5;
        switch (offset) {
            case 0:
                chunk = ((current & 0xF8) >>> 3);
                output.append(lookupTable.charAt(chunk));
                break;
            case 1:
                chunk = (((previous & 0x07) << 2) | ((current & 0xC0) >>> 6));
                output.append(lookupTable.charAt(chunk));
                chunk = ((current & 0x3E) >>> 1);
                output.append(lookupTable.charAt(chunk));
                break;
            case 2:
                chunk = (((previous & 0x01) << 4) | ((current & 0xF0) >>> 4));
                output.append(lookupTable.charAt(chunk));
                break;
            case 3:
                chunk = (((previous & 0x0F) << 1) | ((current & 0x80) >>> 7));
                output.append(lookupTable.charAt(chunk));
                chunk = ((current & 0x7C) >>> 2);
                output.append(lookupTable.charAt(chunk));
                break;
            case 4:
                chunk = (((previous & 0x03) << 3) | ((current & 0xE0) >>> 5));
                output.append(lookupTable.charAt(chunk));
                chunk = (current & 0x1F);
                output.append(lookupTable.charAt(chunk));
                break;
        }
    }