Lighten or darken a hex color - javascript

I'm attempting to convert this piece of Javascript to VB.net code, and I'm having some trouble getting it to work. All the JS does is some math/byte operations, so I don't think I'm going beyond the scope of either language. Here the original code, sourced from:
Pimp Trizkit's Colour Shading Code
function shadeColor2(color, percent) {
var f=parseInt(color.slice(1),16),t=percent<0?0:255,p=percent<0?percent*-1:percent,R=f>>16,G=f>>8&0x00FF,B=f&0x0000FF;
return "#"+(0x1000000+(Math.round((t-R)*p)+R)*0x10000+(Math.round((t-G)*p)+G)*0x100+(Math.round((t-B)*p)+B)).toString(16).slice(1);}
And here's what I've attempted to convert it to:
Public Function LightColor(color As String, percent As Integer) As Color
Dim f As Integer = Convert.ToInt32(color.Substring(1), 16)
Dim t As Integer
If percent < 0 Then
t = 0
Else
t = 255
End If
Dim p As Integer
If percent < 0 Then
p = percent * -1
Else
p = percent
End If
Dim R As Integer = f >> 16
Dim G As Integer = f >> 8 And &HFF
Dim B As Integer = f And &HFF
Dim finalColor As String = "#" + (Convert.ToString( _
(&H1000000 + (Math.Round((t - R) * p) + R) * &H10000 + _
(Math.Round((t - G) * p) + G) * &H100 + _
(Math.Round((t - B) * p) + B))) _
).Substring(1)
Me.txtID.Text = finalColor
Return ColorTranslator.FromHtml(finalColor)
End Function
I would greatly appreciate some help regarding my amateur conversion and whether it could work, I've researched the relevant JS syntax but I'm not sure whether I changed it properly.
After running my code with these parameters:
LightColor("#2980b9", 20)
I obtain a 8-digit hex color (#00642865) which is not even a color-I think I have some problems with the formatting of the hex output.

I'm not exactly sure why your code fails, but I do see some potential pitfalls. The most obvious is the percent parameter. This should be a double or a single as the accepted range is >= -1.0 and <= +1.0.
I've created a simple .net fiddle, available here: https://dotnetfiddle.net/QhowPP
Public Shared Function LightColor(htmlColor As String, percent As Double) As Color
If (String.IsNullOrEmpty(htmlColor)) Then
Throw New ArgumentNullException("htmlColor")
ElseIf ((percent < -1D) Or (percent > +1D)) Then
Throw New ArgumentOutOfRangeException("percent")
End If
Dim c = ColorTranslator.FromHtml(htmlColor)
Dim f = Int32.Parse(htmlColor.Substring(1), Globalization.NumberStyles.AllowHexSpecifier)
Dim t = If((percent < 0), 0, 255)
Dim p = If((percent < 0), (percent * -1), percent)
Dim result = ("#" & CInt(
&H1000000 + (Math.Round((t - c.R) * p) + c.R) *
&H10000 + (Math.Round((t - c.G) * p) + c.G) *
&H100 + (Math.Round((t - c.B) * p) + c.B)
).ToString("X").Substring(1))
Return ColorTranslator.FromHtml(result)
End Function
C#:
public static Color LightColor(String htmlColor, Double percent)
{
if (String.IsNullOrEmpty(htmlColor))
{
throw new ArgumentNullException("htmlColor");
}
else if ((percent < -1D) | (percent > +1D))
{
throw new ArgumentOutOfRangeException("percent");
}
var c = ColorTranslator.FromHtml(htmlColor);
var f = Int32.Parse(htmlColor.Substring(1), System.Globalization.NumberStyles.AllowHexSpecifier);
var t = ((percent < 0) ? 0 : 255);
var p = ((percent < 0) ? (percent * -1) : percent);
var result = ("#" + ((Int32)(
0x1000000 + (Math.Round((t - c.R) * p) + c.R) *
0x10000 + (Math.Round((t - c.G) * p) + c.G) *
0x100 + (Math.Round((t - c.B) * p) + c.B)
)).ToString("X").Substring(1));
return ColorTranslator.FromHtml(result);
}

Related

variable input becoming nullified and breaking .charAt[]

https://jsfiddle.net/2L4t9saq/180/ is my fiddle
most of the code is just useless, ill just post the stuff that matters
var baseConverter = function(r, e, n) {
var o = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (e <= 0 || e > o.length || n <= 0 || n > o.length) return console.log("Base unallowed"), null;
var l, t = 0;
if (10 != e) {
var a = r.length;
for (l = 0; l < a; l++) {
var u, f = -1;
for (u = 0; u < o.length; u++)
if (r[l] == o[u]) {
f = 1;
break
}
if (u >= e) return console.log("Symbol unallowed in baseform"), null;
if (-1 == f) return console.log("Symbol not found"), null;
var s = a - l - 1;
t += 0 == s ? u : u * Math.pow(e, s)
}
} else t = parseInt(r);
if (10 != n) {
for (var g = []; t > 0;) {
var i = t % n;
if (i < 0 || i >= o.length) return console.log("Out of bounds error"), null;
g.push(o[i]), t = parseInt(t / n)
}
return g.reverse().toString().replace(/,/g, "")
}
return t.toString()
}
var b36torgba = function(input) {
for (var i = 1; i < (input.length / 8) + 1; i++) {
var arr = input
var r = arr.charAt[0 + (i - 1) * 8] + "" + arr.charAt[1 + (i - 1) * 8]
var g = arr.charAt[2 + (i - 1) * 8] + "" + arr.charAt[3 + (i - 1) * 8]
console.log(g.charAt[2])
var b = arr.charAt[4 + (i - 1) * 8] + "" + arr.charAt[5 + (i - 1) * 8]
console.log(b)
var a = arr.charAt[6 + (i - 1) * 8] + "" + arr.charAt[7 + (i - 1) * 8]
console.log(a)
var rrgba = baseConverter(r, 36, 10)
var grgba = baseConverter(r, 36, 10)
var brgba = baseConverter(r, 36, 10)
var argba = baseConverter(r, 36, 10)
var bigMessOfAVariable = "rgba(" + rrgba + "," + grgba + "," + brgba + "," + argba + "),"
return bigMessOfAVariable;
}
}
you can ignore the top function, all it is is a base converter script, that takes in three inputs, an input, the base its in, and the base it should be converted to: eg baseConverter(73,36,10) will output 255.
now, the problem is with my b36torgba function.
it will take in a string, which is guaranteed to have a length that is either 0, 8, or a multiple of 8, this is just standardization to make sure everything runs smoothly, without having 700 indexOf[] functions.
it takes in the input, and divides it by 8, this tells the function how many bytes it has to go through, and how many it will spit out, so a string "[7300002S7300002S]" should (divided by 8) output 2, therefore the script runs 2 iterations.
currently, it should be taking in the string, and assigning each group of 2 characters (again standard) to a specific variable, this will allow it to all be put in the end and outputted as the same string but in base 10 rgba (hence 73 being use, 73 in base 36 is 255), but before it can do any of that, it breaks when it tries to find the characters in a string, saying this syntax error:
Uncaught TypeError: Cannot read property '0' of undefined
at b36torgba ((index):40)
at window.onload ((index):55)
why does it break as soon as it tries to feed the string into my charAt()'s?
ps: i do understand that the code in its current state, if it worked, it'd only output the rgba value of the last 8 characters
Easy mistake. You're using charAt (which is a function) by doing charAt[index] (using square brackets), rather than charAt(index) (using round brackets). Fixing that up should solve your issue.
Also - you're calling the function by doing b36torgba(["7300002S7300002S"]) in your JSFiddle, and trying to do string manipulation on it. Since ["7300002S7300002S"] is an array, not a string, .charAt() won't work on it. Try calling the function by doing b36torgba("7300002S7300002S") instead.

Output Stops and Debug doesn't work

Working on a "Ultimate Colour Converter" just as something to do and I can get can the colour models to convert to HSL but for some reason when I convert HSL back, the whole thing breaks. I can't even submit it again.
I have also added a bunch of debug lines in the code where it broke but nothing gets reported to console.
My current project can be found here: http://codepen.io/spedwards/pen/ikJxH or http://jsfiddle.net/spedwards/se5yU/
As the code is really long, I'll refrain from posting the whole thing but just a segment of it.
else if (type == 'hsl') {
hsl = type;console.debug(hsl = type);
/* START RGB */
c = type.slice(4).split(',');console.debug('Removed first 4 chars');
c[2] = c[2].substring(0, c[2].length - 1);console.debug('Removed last bracket');
c = hslToRgb(c[0],c[1],c[2]);console.debug('Convert to RGB');
rgb = 'rgb(' + c.join() + ')';console.debug('Sets RGB');
/* END RGB */
/* START RGBA */
rgba = (rgb.substring(0, rgb.length - 1) + ',1)').splice(3,0,'a');console.debug('Sets RGBA');
/* END RGBA */
/* START HEX */
hex = '#';console.debug('Starts hex');
for (i=0;i<3;i++) {
c[i] = +c[i];console.debug('Coerces to number: ' + i);
hex += (c[i] < 16 ? "0" : "") + c[i].toString(16).toUpperCase();console.debug('Sets hex part: ' + i);
}
/* END HEX */
}
function hslToRgb(h, s, l){
var r, g, b;
if(s == 0){
r = g = b = l; // achromatic
}else{
function hue2rgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
I should note, type comes in as hsl(0,0,1) or whatever is being input.
I found what my problem was. I had forgotten to change type == 'hsl' to colourType == 'hsl'.
All works now.

Pythagorean Triples Formula in Javascript - Project Euler Prob 9

I'm trying to solve the Project Euler Problem 9 :
A Pythagorean triplet is a set of three natural numbers, a < b < c,
for which, a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c =
1000. Find the product abc.
I looked on Wikipedia for the formula to find Pythagorean triples and tried to translate it into code. The problem is that the code is outputting the wrong answer, but I think that the code is correct.
var a, b, c;
var pos1, pos2, pos3;
var ans1, ans2, ans3;
for(var n=2; n<=20000; n++) {
a = 2 * n + 1;
b = 2 * n * (n +1);
c = 2 * n * (n +1) + 1;
if(a<b<c) {
if(a^2 + b^2 === c^2) {
pos1 = a;
pos2 = b;
pos3 = c;
}
if(a + b + c ===1000) {
ans1 = a;
ans2 = b;
ans3 = c;
}
}
}
console.log(ans1 + " " + ans2 + " " + ans3);
This is a solution
var a;
var c;
for (var b = 1; b < 1000; b += 1) {
a = (500000 - 1000 * b) / (1000 - b);
if (Math.floor(a) === a) {
c = 1000 - a - b;
break;
}
}
console.log(a, b, c);
Result is 375 200 425
on jsfiddle
Pythagoras
a2 + b2 = c2
Also we have
a + b + c = 1000
algebra, rearrange c to left
c = 1000 - (a + b)
insert c back in pythagoras
a2 + b2 = (1000 - (a + b))2
multiply out
a2 + b2 = 1000000 - 2000 * (a + b) + (a + b)2
multiply out
a2 + b2 = 1000000 - 2000 * (a + b) + a2 + 2 * a * b + b2
rearrange a2 + b2 to simplify
0 = 1000000 - 2000 * (a + b) + 2 * a * b
rearrange unknowns to left
2000 * (a + b) - 2 * a * b = 1000000
simplify, / 2
1000 * (a + b) - a * b = 500000
factorsize
a(1000 - b) + 1000 * b = 500000
rearrange
a(1000 - b) = 500000 - 1000 * b
a = (500000 - 1000 * b) / (1000 - b)
now input b, calculate a and test if a is an integer as required by Pythagorean Triples
TGarr, here is an explanation to Xotic750's answer.
I don't really understand how you created the algorithm. Why is a = to (500000 - 1000 * b) / (1000 - b) ...
He started with a^2 + b^2 = c^2, and a + b + c = 1000, and combined them because the problem on projecteuler states that there is only 1 set of numbers where both of these statments will be true. Here's how he combined them. He solved the second equation for c to be c = 1000 - (a + b). Then he plugged that into the first equation so that it became a^2 + b^2 = (1000 - (a + b))^2. He continued until he was able to solve the entire equation for a. Once he was able to do that, he was able to make a single for loop that increases b, which is much simpler and more elegant than many other options.
why is the if statement's conditions set to Math.floor(a) === a?
This just means "is a, rounded down to its nearest integer, the same as a?" In other words, is a an integer? (copy his code, and add console.log ( a ); above the if statement. That might help you understand that bit of code) Since he was able to solve the equation for a, all he had to do was plug in different numbers for b, and as soon as the outcome was an integer, he'd have the answer. Or at least he'd know what a and b c = 1000 - a - b; tells him what c is, and that's all she wrote.
Here is another solution with less code:
for(var a = 1; a < 500; a++){
for(var b = a; b < 1000; b++){
var c = Math.sqrt(a * a + b * b);
if(c > b && Number.isInteger(c) && a + b + c == 1000){
console.log(a * b * c);
}
}
}
The result is: 31875000 :)
You can't calculate powers like that.
Use Math.pow(a,2) to calculate a^2
var a, b, c;
var pos1, pos2, pos3;
var ans1, ans2, ans3;
for(var n=2; n<=20000; n++) {
a = 2 * n + 1;
b = 2 * n * (n +1);
c = 2 * n * (n +1) + 1;
if(a<b<c) {
if(Math.pow(a,2) + Math.pow(b,2) === Math.pow(c,2)) {
pos1 = a;
pos2 = b;
pos3 = c;
}
if(a + b + c ===1000) {
ans1 = a;
ans2 = b;
ans3 = c;
}
}
}
console.log(ans1 + " " + ans2 + " " + ans3);
eq 1 : a2 + b2 = c2
eq 2 : a + b + c = 1000
From eq 1 and eq 2 we can have
eq 3 : c = 1000 - a - b
Substitute the value of c from eq 3 into eq 1 we get :
eq 4 : a2 + b2 = (1000 - a - b)2
R.H.S of eq 4 is a trinomial squared. We know that square of a trinomial of such kind is
(a - b - c)2 = a2 + b2 + c2 – 2ab + 2bc – 2ca
We get :
a2 + b2 = 10002 + a2 + b2 – 2*1000*a + 2*a*b – 2*b*1000
Now we simplify to get a to the L.H.S
a = (10002 - 2*1000*b)/(2*1000*b)
Now I can use this to find out value of a where it is an integer and then use Math.sqrt( aa + bb ) to calculate the value of c. Then I can check if a+b+c==1000 holds to be true.
My solution:
public class ProjectEuler9 {
public static void main(String[] args) {
long start = System.nanoTime();
double a;
for(int b=1; b<1000; b++){
a = ( (Math.pow(1000, 2) - 2000*b ) / (2000- 2*b) );
if(Math.floor(a) == a) {
// a is an integer
double c = Math.sqrt((a*a + b*b));
System.out.println("a : " + a + " b :" + b + " c : " + c);
long product = (long) (a*b*c);
System.out.println("product abc : " + product);
break;
} else {
//a is not an integer.
}
}
long stop = System.nanoTime();
System.out.println("\nTime: " + (stop - start) / 1000 + " ns");
}
}
Output :
a : 375.0 b :200 c : 425.0
product abc : 31875000
Time: 3714 ns

Is there a library to generate random numbers according to a beta distribution for JavaScript?

I need to generate random numbers from JavaScript within the Beta probability distribution. I've Googled but can't find any libraries that appear to support this.
Can anyone suggest where I can find a library or code snippet that will do this?
The jStat library has functions to sample from a beta distribution, as well as many other distributions.
var random_num = jStat.beta.sample( alpha, beta );
My translation. It's pretty much word for word, so it's probably not the most idiomatic javascript.
// javascript shim for Python's built-in 'sum'
function sum(nums) {
var accumulator = 0;
for (var i = 0, l = nums.length; i < l; i++)
accumulator += nums[i];
return accumulator;
}
// In case you were wondering, the nice functional version is slower.
// function sum_slow(nums) {
// return nums.reduce(function(a, b) { return a + b; }, 0);
// }
// var tenmil = _.range(1e7); sum(tenmil); sum_slow(tenmil);
// like betavariate, but more like R's name
function rbeta(alpha, beta) {
var alpha_gamma = rgamma(alpha, 1);
return alpha_gamma / (alpha_gamma + rgamma(beta, 1));
}
// From Python source, so I guess it's PSF Licensed
var SG_MAGICCONST = 1 + Math.log(4.5);
var LOG4 = Math.log(4.0);
function rgamma(alpha, beta) {
// does not check that alpha > 0 && beta > 0
if (alpha > 1) {
// Uses R.C.H. Cheng, "The generation of Gamma variables with non-integral
// shape parameters", Applied Statistics, (1977), 26, No. 1, p71-74
var ainv = Math.sqrt(2.0 * alpha - 1.0);
var bbb = alpha - LOG4;
var ccc = alpha + ainv;
while (true) {
var u1 = Math.random();
if (!((1e-7 < u1) && (u1 < 0.9999999))) {
continue;
}
var u2 = 1.0 - Math.random();
v = Math.log(u1/(1.0-u1))/ainv;
x = alpha*Math.exp(v);
var z = u1*u1*u2;
var r = bbb+ccc*v-x;
if (r + SG_MAGICCONST - 4.5*z >= 0.0 || r >= Math.log(z)) {
return x * beta;
}
}
}
else if (alpha == 1.0) {
var u = Math.random();
while (u <= 1e-7) {
u = Math.random();
}
return -Math.log(u) * beta;
}
else { // 0 < alpha < 1
// Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
while (true) {
var u3 = Math.random();
var b = (Math.E + alpha)/Math.E;
var p = b*u3;
if (p <= 1.0) {
x = Math.pow(p, (1.0/alpha));
}
else {
x = -Math.log((b-p)/alpha);
}
var u4 = Math.random();
if (p > 1.0) {
if (u4 <= Math.pow(x, (alpha - 1.0))) {
break;
}
}
else if (u4 <= Math.exp(-x)) {
break;
}
}
return x * beta;
}
}
Partially testable with means, which are easily calculated:
function testbeta(a, b, N) {
var sample_mean = sum(_.range(N).map(function() { return rbeta(a, b); })) / N;
var analytic_mean = a / (a + b);
console.log(sample_mean, "~", analytic_mean);
}
testbeta(5, 1, 100000);
You can convert this Python code to JS:
SG_MAGICCONST = 1.0 + _log(4.5)
LOG4 = log(4.0)
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
# Reflection to right half of complex plane
if z < 0.5:
return pi / sin(pi*z) / gamma(1.0-z)
# Lanczos approximation with g=7
az = z + (7.0 - 0.5)
return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
0.9999999999995183,
676.5203681218835 / z,
-1259.139216722289 / (z+1.0),
771.3234287757674 / (z+2.0),
-176.6150291498386 / (z+3.0),
12.50734324009056 / (z+4.0),
-0.1385710331296526 / (z+5.0),
0.9934937113930748e-05 / (z+6.0),
0.1659470187408462e-06 / (z+7.0),
])
def gammavariate(self, alpha, beta):
"""Gamma distribution. Not the gamma function!
Conditions on the parameters are alpha > 0 and beta > 0.
The probability distribution function is:
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha
"""
# alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
# Warning: a few older sources define the gamma distribution in terms
# of alpha > -1.0
if alpha <= 0.0 or beta <= 0.0:
raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
random = self.random
if alpha > 1.0:
# Uses R.C.H. Cheng, "The generation of Gamma
# variables with non-integral shape parameters",
# Applied Statistics, (1977), 26, No. 1, p71-74
ainv = _sqrt(2.0 * alpha - 1.0)
bbb = alpha - LOG4
ccc = alpha + ainv
while 1:
u1 = random()
if not 1e-7 < u1 < .9999999:
continue
u2 = 1.0 - random()
v = _log(u1/(1.0-u1))/ainv
x = alpha*_exp(v)
z = u1*u1*u2
r = bbb+ccc*v-x
if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= _log(z):
return x * beta
elif alpha == 1.0:
# expovariate(1)
u = random()
while u <= 1e-7:
u = random()
return -_log(u) * beta
else: # alpha is between 0 and 1 (exclusive)
# Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
while 1:
u = random()
b = (_e + alpha)/_e
p = b*u
if p <= 1.0:
x = p ** (1.0/alpha)
else:
x = -_log((b-p)/alpha)
u1 = random()
if p > 1.0:
if u1 <= x ** (alpha - 1.0):
break
elif u1 <= _exp(-x):
break
return x * beta
def betavariate(alpha, beta):
if y == 0:
return 0.0
else:
return y / (y + gammavariate(beta, 1.0))
It's directly from the Python source code (with slight modifications), but it should be easy to convert.
See stdlib, which includes seedable PRNGs for many distributions, including the beta distribution. For example, within the stdlib development environment,
var beta = require( '#stdlib/random/base/beta' );
var r = beta( 2.0, 5.0 );
// returns <number>
Otherwise, see the source code which is released under an Apache license.
http://mbostock.github.com/d3/ex/stack.html
You have an example of generating stacked bar chart layers using gamma distributions. Quiet close to what you are looking for I guess.

IP-addresses stored as int results in overflow?

I'm writing a chat-server in node.js, and I want to store connected users IP-addresses in a mysql database as (unsigned) integers.
I have written a javascript method to convert an ip-address as string to an integer. I get some strange results however.
Here is my code:
function ipToInt(ip) {
var parts = ip.split(".");
var res = 0;
res += parseInt(parts[0], 10) << 24;
res += parseInt(parts[1], 10) << 16;
res += parseInt(parts[2], 10) << 8;
res += parseInt(parts[3], 10);
return res;
}
When I run call the method as ipToInt("192.168.2.44"); the result I get is -1062731220.
It seems like an overflow has occurred, which is strange, because the expected output (3232236076) is inside the number range in javascript (2^52).
When I inspect -1062731220 in binary form, I can see the 3232236076 is preserved, but filled with leading 1's.
I'm not sure, but I think the problem is with signed vs. unsigned integers.
Can any of you explain what is going on?
And possibly how to parse -1062731220 back to an string ip?
Why is the converted IP negative?
It's NOT an overflow. The first part of your IP address is 192 which converts to 11000000 in binary. You then shift that all the way to the left. When there is a 1 in the leftmost position of a 32 bit number, it's negative.
How do you convert back to a string?
Do the same thing you did to convert from a string but in reverse. Shift right (and mask)!
function intToIP(int) {
var part1 = int & 255;
var part2 = ((int >> 8) & 255);
var part3 = ((int >> 16) & 255);
var part4 = ((int >> 24) & 255);
return part4 + "." + part3 + "." + part2 + "." + part1;
}
Why reinvent the wheel? From Google:
OR, you can use what I found here:
http://javascript.about.com/library/blipconvert.htm
function dot2num(dot)
{
var d = dot.split('.');
return ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]);
}
function num2dot(num)
{
var d = num%256;
for (var i = 3; i > 0; i--)
{
num = Math.floor(num/256);
d = num%256 + '.' + d;
}
return d;
}
The result of the "<<" operator is always a signed, 32-bit integer, as per the spec.
When you shift back, use ">>>" to do an unsigned right shift.
You might also find this pattern useful:
ip.toLong = function toInt(ip){
var ipl=0;
ip.split('.').forEach(function( octet ) {
ipl<<=8;
ipl+=parseInt(octet);
});
return(ipl >>>0);
};
ip.fromLong = function fromInt(ipl){
return ( (ipl>>>24) +'.' +
(ipl>>16 & 255) +'.' +
(ipl>>8 & 255) +'.' +
(ipl & 255) );
};
If you're using something like node.js where you can add functionality through something like Npm then you can simply do:
npm install ip
To get that functionality from the source which is here:
https://github.com/indutny/node-ip/blob/master/lib/ip.js
You will also get a bunch of other IP utility functions with that.
You shifted left to get the original number - which is just 4 sets of bits regardless of the sign.
Shift right to get back to the IP. Doesn't matter what the sign is.
const ip2int = (x) => (x.split('.').reduce((a, v) => ((a << 8) + (+v)), 0) >>> 0);
One-Liner:
const ipToLong = ip => ip.split('.').map(parseFloat).reduce((total, part) => total * 256 + part);
Use this
function num2string(ip) {
return [24,16,8,0].map(n => (ip >> n) & 0xff).join(".")
}
function string2num(ip) {
return ip.split(".").reduce((sum,x,i) => sum + (x << 8*(3-i)), 0)
}
IP Addresses in the V4 space are unsigned 32 bit numbers, hence the IP address of FF.FF.FF.FF is 2^32 and cannot be greater then that number. Please see:
This stack overflow article on the same subject
To turn that number back into an IP address you must break the number down into its 4 parts since each byte is one octet of the address so convert the number to hex and then parse out each pair. You may or may not have to add a leading zero for the first octet.
Additionally you may have to deal with byte order of the integer ( endien issues ) but since most systems are intel based these days you might not have to deal with that.
var aaa = Number("0b"+ "192.168.2.44".split(".").map(
function(dec){
return ("00000000" + Number(dec).toString(2)).slice(-8);
}).join(""));
aaa.toString(2).match(/.{1,8}/g).map(
function(bin){
return Number("0b"+bin);
}).join(".");
I revised Evan's final answer a bit, particularly dot2num. It functions the same but might be more readable and is marginally slower.
function ip2num(ip) {
var parts = ip.split('.');
var num = 0;
num += d[0] * Math.pow(2, 24);
num += d[1] * Math.pow(2, 16);
num += d[2] * Math.pow(2, 8);
num += d[3];
return num;
}
function num2ip(num) {
var ip = num % 256;
for (var i=3; i > 0; i--) {
num = Math.floor(num / 256);
ip = num % 256 + '.' + ip;
}
return ip;
}
Try this solution, it might help:
function IpToInteger(ipAddr)
{
var parts = ipAddr.split('.');
return (((parts[0] ? parts[0] << 24 : 0) |
(parts[1] ? parts[1] << 16 : 0) |
(parts[2] ? parts[2] << 8 : 0) |
(parts[3])) >>> 0);
}
function IpAddressToLong(ip){
return ip.split('.').map((octet, index, array) => {
return parseInt(octet) * Math.pow(256, (array.length - index - 1));
}).reduce((prev, curr) => {
return prev + curr;
});
}
Taken from repo
function ip2num(ip) {
var d = ip.split(".");
var num = 0;
num += Number(d[0]) * Math.pow(256, 3);
num += Number(d[1]) * Math.pow(256, 2);
num += Number(d[2]) * Math.pow(256, 1);
num += Number(d[3]);
return num;
}
function num2ip(num) {
var ip = num % 256;
for (var i = 3; i > 0; i--) {
num = Math.floor(num / 256);
ip = (num % 256) + "." + ip;
}
return ip;
}
console.log(ip2num("192.168.0.1"));
console.log(num2ip(3232235521))
<h1>YOU IS WELCOME</h1>

Categories

Resources