Equivalent JavaScript syntax - javascript

I am new to javascript and wondering what is the equivalent javascript syntax for below Java Code.
public static void crcValue(byte[] value) {
byte crc = 0;
for (int i = 0; i < 15; i++) {
crc = (byte) (value[i] + crc);
}
value[15] = (byte) (crc & 255);
}
I have tried the below code.
var cmd = new ArrayBuffer(16);
function crcValue(cmd){
var crc;
for (var i = 0; i < 15; i++) {
crc = cmd[i] + crc;
}
cmd[16] = crc & 255 ;
}

Related

How to compile this C code to WebAssembly correctly?

I have the C code:
int edges_start[3000];
int edges_end[3000];
float edges_len[3000];
int g_links_id[1000][100];
float g_links_weight[1000][100];
int cache_id[1000];
float cache_distance[1000];
int cache_prev[1000];
int cache_links_id[1000][100];
float cache_links_weight[1000][100];
int queue_id[1000];
float queue_distance[1000];
int queue_prev[1000];
int queue_links_id[1000][100];
float queue_links_weight[1000][100];
void* memcpy(char* dst, char* src, int count) {
while(count--) *dst++ = *src++;
}
void init_cpp() {
for (int i=0; i < 1000; i++) {
cache_id[i] = -2;
queue_id[i] = -2;
cache_distance[i] = 100000;
queue_distance[i] = 100000;
cache_prev[i] = -2;
queue_prev[i] = -2;
for (int j=0; j < 100; j++) {
queue_links_id[i][j] = -2;
queue_links_weight[i][j] = 100000;
cache_links_id[i][j] = -2;
cache_links_weight[i][j] = 100000;
}
}
}
void init_edges_cpp() {
for (int i=0; i < 3000; i++) {
edges_start[i] = -2;
edges_end[i] = -2;
edges_len[i] = -2.0;
}
for (int i=0; i < 1000; i++) {
for (int j=0; j < 100; j++) {
g_links_id[i][j] = -2;
g_links_weight[i][j] = -2.0;
}
}
}
void add_edge_cpp(int index, int start, int end, float len) {
edges_start[index] = start;
edges_end[index] = end;
edges_len[index] = len;
}
void fill_graph_cpp() {
for (int i=0; i < 3000; i++) {
int s = edges_start[i];
int e = edges_end[i];
float len = edges_len[i];
if (s == -2) {
break;
}
int links_len = 0;
for (int j=0; j < 100; j++) {
if (g_links_id[s][j] == -2) {
links_len = j;
break;
}
}
g_links_id[s][links_len] = e;
g_links_weight[s][links_len] = len;
for (int j=0; j < 100; j++) {
if (g_links_id[e][j] == -2) {
links_len = j;
break;
}
}
g_links_id[e][links_len] = s;
g_links_weight[e][links_len] = len;
}
}
void get_dists_cpp(int a, int L) {
int i = L;
while (--i >= 0) {
for (int j = 0; j < 100; j++) {
//console.log()
if (g_links_id[i][j] == -2) {
break;
}
cache_links_id[i][j] = g_links_id[i][j];
cache_links_weight[i][j] = g_links_weight[i][j];
}
cache_id[i] = i;
}
queue_id[0] = cache_id[a];
cache_distance[a] = 0;
queue_distance[0] = cache_distance[a];
queue_prev[0] = queue_prev[a];
for (int j=0; j < 100; j++) {
queue_links_id[0][j] = cache_links_id[a][j];
queue_links_weight[0][j] = cache_links_weight[a][j];
}
i=0;
int queue_len = 1;
while (i < queue_len) {
int node_id = queue_id[i];
float node_distance = queue_distance[i];
int node_prev = queue_prev[i];
int j=0;
for (int k=0; k < 100; k++) {
if (queue_links_id[i][k] == -2) {
j=k;
break;
}
}
while (--j >= 0) {
int link_id = queue_links_id[i][j];
float link_weight = queue_links_weight[i][j];
int c_id = cache_id[link_id];
float c_distance = cache_distance[link_id];
int c_prev = cache_prev[link_id];
float d = node_distance + link_weight;
if (d < c_distance) {
cache_prev[link_id] = node_id;
cache_distance[link_id] = d;
int last_ind = queue_len;
queue_id[last_ind] = cache_id[link_id];
queue_distance[last_ind] = cache_distance[link_id];
for (int k=0; k < 100; k++) {
if (cache_links_id[link_id][k] == -2) {
break;
}
queue_links_id[last_ind][k] = cache_links_id[link_id][k];
queue_links_weight[last_ind][k] = cache_links_weight[link_id][k];
}
queue_prev[last_ind] = cache_prev[link_id];
queue_len++;
}
}
i++;
}
}
int get_edges_start(int index) {
return edges_start[index];
}
float get_cache_distance(int index) {
return cache_distance[index];
}
int get_cache_prev(int index) {
return cache_prev[index];
}
int main() {
init_edges_cpp();
init_cpp();
add_edge_cpp(0, 0, 2, 1);
add_edge_cpp(1, 0, 1, 1);
add_edge_cpp(2, 1, 2, 1);
add_edge_cpp(3, 2, 3, 1);
add_edge_cpp(4, 2, 4, 1);
add_edge_cpp(5, 3, 4, 1);
fill_graph_cpp();
get_dists_cpp(0, 5);
/*
for (int i=0; i < 10; i++) {
cout << i << " " << get_cache_distance(i) << " " << get_cache_prev(i) << endl;
}
*/
return 0;
}
It works correct, you can check it here
But, when I tried to compile it to wasm with this website
I put in the left field this code: https://pastebin.com/NG10Z0jX
And in the right field that js code:
var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);
var wasm_module = wasmInstance.exports
wasm_module.main();
for (var i=0; i < 5; i++) {
var c1 = wasm_module.get_cache_distance(i);
var c2 = wasm_module.get_cache_prev(i);
log(i+" " +c1 + " " + c2)
}
It returned wrong output:
vert: 0 dist: 0 prev -2
vert: 1 dist: 100000 prev -2
vert: 2 dist: 100000 prev -2
vert: 3 dist: 100000 prev -2
vert: 4 dist: 100000 prev -2
It should return this:
vert: 0 dist: 0.000000 prev: -2
vert: 1 dist: 1.000000 prev: 0
vert: 2 dist: 1.000000 prev: 0
vert: 3 dist: 2.000000 prev: 2
vert: 4 dist: 2.000000 prev: 2
How to compile this C code to WebAssembly correctly?
The answer is to put this in C code:
void* memcpy(char* dst, char* src, int count) {
void* p=dst;
while(count--) *dst++ = *src++;
return p;
}

Browse is slowing down for a JavaScript code

I'm working on a JavaScript library for me. This library will help you to convert a binary number into a decimal number. The default JavaScript function can only convert before point (integers). But this code will convert floating numbers also (hopefully).
In order to test this when I ran this code on Firefox returned,
This page is slowed down your browser.
& Google Chrome returned nothing but just loading.
So I want to know what is the problem??
Here is my code
var x = "101.11";
var r = 0;
var ra = 0;
for (var i = 0; i < x.length; ++i) {
if (x.charAt(i) == ".") {
var Ap = i;
}
}
for (var j = 0; j < (x.length - Ap); ++j) {
var a = x.charAt(j);
r = r + a * Math.pow(2, ((x.length - Ap - 1) - j));
}
for (var k = Ap + 1;
(x.length - Ap) < k; ++k) {
var b = x.charAt(k);
ra = ra + b * Math.pow(2, (Ap - k));
}
document.write(r);
if (ra <= 0) {
document.write("." + ra);
}
Here is the solution. I'm very much thankful to you people.
/*
It's a dumb library for converting binary fraction number into a desimal number.
Created by : Adib Rahman
Last update : 12:36 30/01/2020
*/
function print(something)
{
document.write(something);
}
var x = "010101010.111";
var r = 0;
var ra = 0;
for(var i=0;i<x.length;++i)
{
if(x.charAt (i)== ".")
{
var Ap=i;
}
}
var beforePoint = (x.length-(x.length-Ap-1))-1;
var afterPoint = x.length-Ap-1;
for(var j=0;j<beforePoint;++j)
{
r = r+(x.charAt(j))*Math.pow(2,(beforePoint-j-1));
}
for(var k=Ap+1;k<x.length;++k)
{
var ra = ra+(x.charAt(k))*Math.pow(2,(Ap-k));
}
//Final Result
if(ra >=0)
{
print(r+ra);
}
else
{
print(r);
}

convert a text to hash in node js

I want to convert a text to hash id of numbers using node js. Already have a java program to convert but same kind of implementation to be done using node js.
Java Code
public static long generateId(String text) {
byte[] buffer = null;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA1");
md.reset();
buffer = text.getBytes(Charsets.UTF_8);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
md.update(buffer);
byte[] digest = md.digest();
String hexStr = "";
for (int i = 0; i < digest.length; i++) {
hexStr += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
}
long hashid = 0;
for (int i = 0; i < hexStr.length(); i++)
hashid += Math.abs((long) Math.pow(27, 10 - i) * ('a' - (1 + hexStr.charAt(i))));
return hashid;
}
I was able to convert into nodejs upto digest after this I am unable to proceed.
function generateHashCode()
{
var text = '9/01/2017'+'xx'+'405'+''+'SDD'+'MDD'+'9';
var crypto = require('crypto');
console.log(crypto.createHash('SHA1').update(text).digest("hex"));
var hexDigest = crypto.createHash('SHA1').update(text).digest("hex");
var hexStr;
}
Kindly help me on this
function generateHashCode(text)
{
// assuming text is UTF-8 encoded
var crypto = require('crypto');
var hexDigest = crypto.createHash('SHA1').update(text).digest(); // this should be .digest() not .digest('hex')
var hexStr = "";
for (var i = 0; i < hexDigest.length; i++) {
hexStr += (((hexDigest[i] - 0x100) & 0xff) + 0x100).toString(16).substr(1); // fixed some math issues here
}
var hashid = 0;
var a = 'a'.charCodeAt(0); // or just var a = 97;
for (var i = 0; i < hexStr.length; i++)
hashid += Math.abs(Math.pow(27, 10 - i) * (a - (1 + hexStr.charCodeAt(i))));
return hashid;
}
console.log(generateHashCode("batman"));

Different Implementation of the same JS program in C++

I recently raised a question about implementing sieve of eratosthenes in Javascript on SO and here's the working answer I got:
function sieve(low, high) {
var primeArray = [], ll = Math.sqrt(high), output = [];
for (var i = 2; i <= high; i++) {
primeArray[i] = true;
}
for (var i = 2; i <= ll; i++) {
if (primeArray[i]) {
for (var j = i * i; j <= high; j += i) {
primeArray[j] = false;
}
}
}
for (var i = 2; i <= ll; i++) {
if(primeArray[i]) {
var segmentStart = Math.ceil(low/i) * i;
// need this test to ensure we are not deleting primes
if (primeArray[segmentStart]) segmentStart += i;
for(var j = segmentStart; j <= high; j+=i) {
primeArray[j] = false;
}
}
}
for(var i = low; i <= high; i++) {
if(primeArray[i]) {
output.push(i);
}
}
return output;
}
console.log(sieve(1, 20));
I tried implementing the same in C++
However the end result is quite different.
My C++ program is somehow ignoring the first 2 prime numbers while maintaining 1 as a prime.
Here's the same program in C++
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int low, high;
cout << "Enter lower bound: ";
cin >> low;
cout << "Enter upper bound: ";
cin >> high;
int root = floor(sqrt(high));
int primes[high];
for(int i = 2; i <= high; i++)
{
primes[i] = true;
}
for (int i = 2; i <= root; i++) {
if (primes[i]) {
for (int j = i * i; j <= high; j += i) {
primes[j] = false;
}
}
}
for (int i = 2; i <= root; i++) {
if(primes[i]) {
int segmentStart = ceil(low/i) * i;
if (primes[segmentStart]) segmentStart += i;
for(int j = segmentStart; j <= high; j+=i) {
primes[j] = false;
}
}
}
for(int i = low; i <= high; i++) {
if(primes[i]) {
cout << i;
}
}
return 0;
}
Found the solution.
low/i division operation in int segmentStart = ceil(low/i) * i; was returning an integer and hence it was ignoring results < 1;
I typecasted i as a double to solve this problem like this:
int segmentStart = ceil(low/(double)i) * i;

Writing WebSocket Server on Java. Issue on Windows 7 64 bits

I having a problem with WebSocket protocol.
When I execute the code when develop (NetBeans) and works fine, even when I execute the jar file still works, but... When I execute the jar on Windows 7 64 bits platform... The WebSocket close by itself.
I'm working on local machine both the server and client, even I deactivate windows firewall and nothing changes.
Even I test with 3 browsers (Firefox, Chrome and Opera) and I fund the same result.
Any ideas?
Code of server listening thread
InputStream listen;
while (true) {
try {
if (socket.isClosed()) {
socket.close();
return;
} else {
listen = socket.getInputStream();
byte[] readData = new byte[1024];
int totalRead = listen.read(readData);
if (totalRead > 0) {
byte[] result = new byte[totalRead];
System.arraycopy(readData, 0, result, 0, totalRead);
String resultString = new String(result);
if (resultString.substring(0, 3).equals("GET")) {
HtmlRequest myRequest = new HtmlRequest(resultString);
caller.push(myRequest);
} else {
caller.push(WebsocketProtocol.decrypt(result, totalRead));
}
}
System.out.println(getName()+": total read -> "+totalRead);
}
}catch(SocketException e){
System.out.println(getName() + ": SocketException "+e.getMessage());
} catch (IOException ex) {
System.out.println(getName() + ": IOException "+ex.getMessage());
} catch (NullPointerException ex){
System.out.println(getName() + ": NullPointerException "+ex.getMessage());
} catch (Exception e) {
System.out.println(getName() + ": Exception "+e.getMessage());
}
}
Code of websocket protocol:
public static byte[] decrypt(byte[] leido, int largo) {
byte rLength = 0;
int rMaskIndex = 2;
int rDataStart = 0;
byte data = leido[1];
byte op = (byte) 127;
rLength = (byte) (data & op);
if (rLength == (byte) 126) {
rMaskIndex = 4;
}
if (rLength == (byte) 127) {
rMaskIndex = 10;
}
byte[] masks = new byte[4];
int j = 0;
int i = 0;
for (i = rMaskIndex; i < (rMaskIndex + 4); i++) {
masks[j] = leido[i];
j++;
}
rDataStart = rMaskIndex + 4;
int messLen = largo - rDataStart;
byte[] message = new byte[messLen];
for (i = rDataStart, j = 0; i < largo; i++, j++) {
message[j] = (byte) (leido[i] ^ masks[j % 4]);
}
return message;
}
public static byte[] encrypt(String message) {
byte[] bytesContent = message.getBytes();
int countFrames = 0;
byte[] frame = new byte[10];
frame[0] = (byte) 129;
if (bytesContent.length <= 125) {
frame[1] = (byte) bytesContent.length;
countFrames = 2;
} else if (bytesContent.length > 125 && bytesContent.length <= 65535) {
frame[1] = (byte) 126;
int largo = bytesContent.length;
frame[2] = (byte) ((largo >> 8) & (byte) 255);
frame[3] = (byte) (largo & (byte) 255);
countFrames = 4;
} else {
frame[1] = (byte) 127;
int largo = bytesContent.length;
frame[2] = (byte) ((largo >> 56) & (byte) 255);
frame[3] = (byte) ((largo >> 48) & (byte) 255);
frame[4] = (byte) ((largo >> 40) & (byte) 255);
frame[5] = (byte) ((largo >> 32) & (byte) 255);
frame[6] = (byte) ((largo >> 24) & (byte) 255);
frame[7] = (byte) ((largo >> 16) & (byte) 255);
frame[8] = (byte) ((largo >> 8) & (byte) 255);
frame[9] = (byte) (largo & (byte) 255);
countFrames = 10;
}
byte[] answer = new byte[countFrames + bytesContent.length];
int currentPosition = 0;
for (int i = 0; i < countFrames; i++) {
answer[currentPosition] = frame[i];
currentPosition++;
}
for (int i = 0; i < bytesContent.length; i++) {
answer[currentPosition] = bytesContent[i];
currentPosition++;
}
return answer;
}
Looks like the fail is about the default character set on JVM on windows 7.
In the call
call java -jar filename.jar
You have to add
call java -Dfile.encoding=UTF-8 -jar filename.jar

Categories