Want to get equivalent python conversion for the following java code.
msg = "any text"
int len = msg == null ? 0 : msg.length ();
if (len > 0) {
byte lb[] = new byte[4];
lb[3] = (byte) (len & 0xFF);
lb[2] = (byte) ((len >> 8) & 0xFF);
lb[1] = (byte) ((len >> 16) & 0xFF);
lb[0] = (byte) ((len >> 24) & 0xFF);
}
Please help.
msg = "any text"
len = len(msg)
lb = []
if len > 0 :
lb.append(len & 0xFF)
lb.append((len >> 8) & 0xFF)
lb.append((len >> 16) & 0xFF)
lb.append((len >> 24) & 0xFF)
for num in reversed(lb):
print (num)
msg = "any text"
length = 0 if msg is None else len(msg)
if length > 0:
lb = []
lb.append((length >> 24) & 0xFF)
lb.append((length >> 16) & 0xFF)
lb.append((length >> 8) & 0xFF)
lb.append((length ) & 0xFF)
newmsg = b''.join(chr(i) for i in lb)
Related
Firstly this questions is inferred from this answer answer .In that answer provides us a splitting a mp3 file with Python . That code is usefull , but for splitting two pieces . For instance if I want to split 30.00 th second to end of the audio , it is cool , but if I want to split from 30.00 to 35.00 it is useless for it . Below of that answer there is a comment about how to trim audio, like I said ,specific piece. When I imply that instructions to code it looked like that :
import struct
import sys
#MP3 frames are not independent because of the byte reservoir. This script does not account for
#that in determining where to do the split.
def SplitMp3(fi, firstSplit_sec,secondSplit_sec, out):
#Constants for MP3
bitrates = {0x0: "free", 0x1: 32, 0x2: 40, 0x3: 48, 0x4: 56, 0x5: 64, 0x6: 80, 0x7: 96, 0x8: 112,
0x9: 128, 0xa: 160, 0xb: 192, 0xc: 224, 0xd: 256, 0xe: 320, 0xf: "bad"}
freqrates = {0x0: 44100, 0x1: 48000, 0x2: 32000, 0x3: "reserved"}
countMpegFrames = 0
frameDuration = 0.026
unrecognizedBytes = 0
firstSplitFrame = int(round(firstSplit_sec / frameDuration))
secondSplitFrame = int(round(secondSplit_sec / frameDuration))
while True:
startPos = fi.tell()
#Check for 3 byte headers
id3Start = fi.read(3)
if len(id3Start) == 3:
if id3Start == b'TAG':
#print ("Found ID3 v1/1.1 header")
fi.seek(startPos + 256)
continue
if id3Start == b'ID3':
#Possibly a ID3v2 header
majorVer, minorVer, flags, encSize = struct.unpack(">BBBI", fi.read(7))
if majorVer != 0xFF and minorVer != 0xFF:
encSize1 = (encSize & 0x7f000000) >> 24
encSize2 = (encSize & 0x7f0000) >> 16
encSize3 = (encSize & 0x7f00) >> 8
encSize4 = (encSize & 0x7f)
if encSize1 < 0x80 and encSize2 < 0x80 and encSize3 < 0x80 and encSize4 < 0x80:
size = ((encSize & 0x7f000000) >> 3) + ((encSize & 0x7f0000) >> 2) + ((encSize & 0x7f00) >> 1) + (encSize & 0x7f)
unsync = (flags >> 7) & 0x1
extendedHeader = (flags >> 6) & 0x1
experimental = (flags >> 5) & 0x1
#print ("Found ID3v2 header")
#print ("version", majorVer, minorVer, unsync, extendedHeader, experimental)
#print ("size", size)
#TODO extendedHeader not supported yet
fi.seek(startPos + 10 + size)
continue
#Check for 4 byte headers
fi.seek(startPos)
headerRaw = fi.read(4)
if len(headerRaw) == 4:
headerWord = struct.unpack(">I", headerRaw)[0]
#Check for MPEG-1 audio frame
if headerWord & 0xfff00000 == 0xfff00000:
#print ("Possible MPEG-1 audio header", hex(headerWord))
countMpegFrames += 1
ver = (headerWord & 0xf0000) >> 16
bitrateEnc = (headerWord & 0xf000) >> 12
freqEnc = (headerWord & 0xf00) >> 8
mode = (headerWord & 0xf0) >> 4
cpy = (headerWord & 0xf)
if ver & 0xe == 0xa and freqEnc != 0xf:
#print ("Probably an MP3 frame")
bitrate = bitrates[bitrateEnc]
freq = freqrates[freqEnc >> 2]
padding = ((freqEnc >> 1) & 0x1) == 1
#print ("bitrate", bitrate, "kbps")
#print ("freq", freq, "Hz")
#print ("padding", padding)
frameLen = int((144 * bitrate * 1000 / freq ) + padding)
#Copy frame to output
fi.seek(startPos)
frameData = fi.read(frameLen)
if (secondSplitFrame >= countMpegFrames) and (countMpegFrames >= firstSplitFrame):
out.write(frameData)
fi.seek(startPos + frameLen)
continue
else:
raise RuntimeError("Unsupported format:", hex(ver), "header:", hex(headerWord))
#If no header can be detected, move on to the next byte
fi.seek(startPos)
nextByteRaw = fi.read(1)
if len(nextByteRaw) == 0:
break #End of file
unrecognizedBytes += 1
#print ("unrecognizedBytes", unrecognizedBytes)
#print ("countMpegFrames", countMpegFrames)
#print ("duration", countMpegFrames * frameDuration, "sec")
When I use this function it produces loosy output . For instance if I want to split 0.0 to 41.00 it gives me 0.00 to 37.00 , and this loosieness is increasing with amount of slice. I've struggled to understand some parts of code . So I am asking how can I solve that loosiness ? Am I missing something ?
Note : I already tried to pydub and similar modules . But they are useless . Always giving memory error and slow . This is really fast .
I couldn't find a solution for loosiness problem therefore I used ffmpeg for slicing .
subprocess.call(["ffmpeg","-i",input_file,"-acodec","copy","-loglevel","quiet","-ss",str(start),"-to",str(end),"-metadata","title={}".format(name),output_file+".mp3"])
I got a system where I would send a command from my host computer using Python Socket (the computer is the server) and the MKR1000 (client) would send back information depends on the command sent.
Unfortunately, the bidirectional communication is unstable. I can guarantee the MKR1000 received the command and (maybe) sending information back, but for some reason, my host computer would not receive the command.
Anyway, this is my first time trying out socket, so I would like some guru to review my code and maybe spot the mistake in here? Thanks a lot.
Python:
import socket
import time
def coor2bytes(coor_fnc):
coorByte = [0, 0, 0, 0, 0, 0]
if (coor_fnc[0] >= 0):
coorByte[0] = (coor_fnc[0] >> 8) & 0xFF # High byte of X
coorByte[1] = coor_fnc[0] & 0xFF # Low byte of X
else:
coor_fnc[0] = coor_fnc[0]*(-1)
coorByte[0] = (coor_fnc[0] >> 8) & 0xFF # High byte of X
coorByte[0] = coorByte[0] ^ 0x80
coorByte[1] = coor_fnc[0] & 0xFF # Low byte of X
if (coor_fnc[1] >= 0):
coorByte[2] = (coor_fnc[1] >> 8) & 0xFF # High byte of Y
coorByte[3] = coor_fnc[1] & 0xFF # Low byte of Y
else:
coor_fnc[1] = coor_fnc[1]*(-1)
coorByte[2] = (coor_fnc[1] >> 8) & 0xFF # High byte of X
coorByte[2] = coorByte[2] ^ 0x80
coorByte[3] = coor_fnc[1] & 0xFF # Low byte of X
if (coor_fnc[2] >= 0):
coorByte[4] = (coor_fnc[2] >> 8) & 0xFF # High byte of Phi
coorByte[5] = coor_fnc[2] & 0xFF # Low byte of Phi
else:
coor_fnc[2] = coor_fnc[2]*(-1)
coorByte[4] = (coor_fnc[2] >> 8) & 0xFF # High byte of Phi
coorByte[4] = coorByte[4] ^ 0x80
coorByte[5] = coor_fnc[2] & 0xFF # Low byte of Phi
return coorByte
def bytes2coor(byte_fnc):
receivedCoor_fnc = [0, 0, 0]
receivedCoor_fnc[0] = ((-1)**(byte_fnc[0]>>7)) * ((byte_fnc[1]) | (((byte_fnc[0]&0x7f)<<8)))
receivedCoor_fnc[1] = ((-1)**(byte_fnc[2]>>7)) * ((byte_fnc[3]) | (((byte_fnc[2]&0x7f)<<8)))
receivedCoor_fnc[2] = ((-1)**(byte_fnc[4]>>7)) * ((byte_fnc[5]) | (((byte_fnc[4]&0x7f)<<8)))
return receivedCoor_fnc
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234)) # bind(ip, port)
print("Done binding.")
s.listen(2)
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
clientsocket.settimeout(1)
while True:
print();
print("What you want to do?")
print("0. Send target")
print("1. Get current coordinate")
print("2. Set current coordinate (not yet implement)")
try:
a = int(input("I choose: "))
except Exception:
print("Error.")
a = -1;
if (a == 0):
coor = [0, 0, 0]
try:
coor[0] = int(input("X: "))
coor[1] = -int(input("y: "))
coor[2] = int(input("phi: "))
coorByte = coor2bytes(coor)
clientsocket.send(bytes([0]))
clientsocket.send(bytes(coorByte))
print("I already sent the target.")
except Exception:
print("Error.")
elif (a == 1):
receive = 0
while (not receive):
try:
clientsocket.send(bytes([1]))
bytesReceived = []
full_msg = []
while (len(full_msg) < 8):
bytesReceived = clientsocket.recv(8)
for x in range(len(bytesReceived)):
full_msg.append(bytesReceived[x])
receivedCoor = bytes2coor(full_msg)
print("coordinate received: " + str(receivedCoor))
receive = 1
except socket.timeout:
print("Time out. Will try again.")
elif (a == 2):
setCoor = [0, 0, 0]
try:
setCoor[0] = int(input("X: "))
setCoor[1] = -int(input("y: "))
setCoor[2] = int(input("phi: "))
setcoorByte = coor2bytes(setCoor)
clientsocket.send(bytes([2]))
clientsocket.send(bytes(setcoorByte))
print("I already sent the new coordinate.")
except Exception:
print("Error.")
else:
print("Not yet implement.")
Arduino:
#include <WiFi101.h>
#include <SPI.h>
// To connect to the server on laptop
char ssid[] = "iPhone";
char pass[] = "00000000";
int status = WL_IDLE_STATUS;
IPAddress server(172,20,10,3);
WiFiClient client;
// Random variable
int a, i, j, k, m;
byte buf0[7];
byte buf1[7];
byte buf2[7];
long start = millis();
int elapsedTime = 0;
int timeout = 0;
void setup() {
// put your setup code here, to run once:
// Serial.begin(115200);
Serial.begin(115200);
Serial1.begin(115200);
// status = WiFi.begin(ssid, pass);
while (status != WL_CONNECTED) {
status = WiFi.begin(ssid, pass);
}
j = client.connect(server, 1234);
while (j != 1) {
j = client.connect(server, 1234);
}
}
void loop()
{
if (client.available()) {
a = client.read();
Serial.print("I got: ");
Serial.println(a);
if (a == 0) { // Send new target to Due
Serial.println("I send target.");
j = 0;
start = millis();
while(j<6) {
elapsedTime = millis() - start;
if (elapsedTime > 1000) {
timeout = 1;
break;
}
if (client.available()>0) {
buf0[j] = client.read();
Serial.println(buf0[j]);
j++;
}
}
if (timeout != 1) {
Serial1.write((byte) 0);
// Send coordinate back to Due
for (i = 0; i<6; i++) {
Serial1.write(buf0[i]);
}
} else {
timeout = 0;
}
} else if (a == 1) {
// Get the coordinate from the Due
Serial.println("I receive coordinate.");
Serial1.write((byte) 1);
k = 0;
start = millis();
while(k < 6) {
elapsedTime = millis() - start;
if (elapsedTime > 1000) {
timeout = 1;
break;
}
if (Serial1.available() > 0) {
buf1[k] = Serial1.read();
Serial.println(buf1[k]);
k++;
}
}
if (timeout != 1) {
for (i=0;i<6;i++) {
client.write(buf1[i]);
delay(10);
}
client.write((byte) 0); // fill in the blank size
delay(10);
client.write((byte) 0);
} else {
timeout = 0;
}
// for (int i = 0; i<8; i++) {
// client.write((byte) 0);
// }
} else if (a == 2) { // set the current coordinnate to be something else.
Serial.println("I set coordinate.");
m = 0;
while(m<6) {
if (client.available()>0) {
buf2[m] = client.read();
Serial.println(buf2[m]);
m++;
}
}
Serial1.write((byte) 2);
// Send coordinate back to Due
for (i = 0; i<6; i++) {
Serial1.write(buf2[i]);
}
} else if (a == 3) { // identify yourself
Serial.println("Identify myself.");
client.write((byte) 1);
}
}
}
If you have time to read through the Arduino code, then you would see that I actually have serial communication between my MKR and Due too. I also can guarantee that the MKR can receive all those data from the Due and not stuck in some infinite loop.
Thank you!
Ok so for some reason if I added a delay right after the MKR connecting to WiFi, before connecting to the server, then everything just works.
I'm trying to create a python websocket class that can connect to a websocket server and I need help writing a function that can mask and unmask data. I have an similar websocket class in PHP that looks like this:
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
function mask($text){
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
So I tried to create the same thing in Python:
def mask(text):
b1 = 0x80 | (0x1 & 0x0f)
length = len(text)
if length <= 125:
header = struct.pack('CC', b1, length)
if length > 125 & length < 65536:
header = struct.pack('CCn', b1, 126, length)
if length <= 65536:
header = struct.pack('CCNN', b1, 127, length)
return header + text
And it returns an error:
Bad char in struct format
If anyone could help me write the function that would be great. Thanks!
I found an really helpful script that did exactly what i needed.
http://sidekick.windforwings.com/2013/03/minimal-websocket-broadcast-server-in.html
I want a normal format for the MAC-Address I got from get_node().
The format I get is 0x0L0xdL0x60L0x76L0x31L0xd6L, I want the 0x deleted and the L-term to a real hex number. It should be 00-0D-60-76-31-D6 .
How can I realize this?
def getNetworkData (self):
myHostname, myIP, myMAC = AU.getHostname()
touple1 = (myMAC & 0xFF0000000000) >> 40
touple2 = (myMAC & 0x00FF00000000) >> 32
touple3 = (myMAC & 0x0000FF000000) >> 24
touple4 = (myMAC & 0x000000FF0000) >> 16
touple5 = (myMAC & 0x00000000FF00) >> 8
touple6 = (myMAC & 0x0000000000FF) >> 0
readableMACadress = hex(touple1) + hex(touple2) + hex(touple3) + hex(touple4) + hex(touple5) + hex(touple6)
print readableMACadress
return myHostname, myIP, readableMACadress
Use
readableMACaddress = '%02X-%02X-%02X-%02X-%02X-%02X' % (touple1, touple2, touple3, touple4, touple5, touple6)
More concisely, you can eliminate the temporary touple variables by using
readableMACaddress = '-'.join('%02X' % ((myMAC >> 8*i) & 0xff) for i in reversed(xrange(6)))
I got the following code in javascript for RSA implementionhttp://www-cs-students.stanford.edu/~tjw/jsbn/:
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
if(m == null) return null;
var c = this.doPublic(m);
if(c == null) return null;
var h = c.toString(16);
if((h.length & 1) == 0) return h; else return "0" + h;
}
// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2(s,n) {
if(n < s.length + 11) { // TODO: fix for utf-8
alert("Message too long for RSA");
return null;
}
var ba = new Array();
var i = s.length - 1;
while(i >= 0 && n > 0) {
var c = s.charCodeAt(i--);
if(c < 128) { // encode using utf-8
ba[--n] = c;
}
else if((c > 127) && (c < 2048)) {
ba[--n] = (c & 63) | 128;
ba[--n] = (c >> 6) | 192;
}
else {
ba[--n] = (c & 63) | 128;
ba[--n] = ((c >> 6) & 63) | 128;
ba[--n] = (c >> 12) | 224;
}
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while(n > 2) { // random non-zero pad
x[0] = 0;
while(x[0] == 0) rng.nextBytes(x);
ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);
}
In the snippets above, it seems that the pkcs1pad2 function is used for padding the message with some random bytes(maybe sth like 0|2|random|0 ) in front of the message.
I'm using the python rsa package (http://stuvel.eu/rsa) for imitating the javascript result, i'm a newbie to python world and have no idea to traslate javascript algorithm code to the python code.
Any help would be appreciated.
Jiee
I know it's a bit late, but in a few days I'll release a new version of my Python-RSA package. That version will include PKCS#1 v1.5 padding, so it should be compatible with your JavaScript code ;-)