RGBA Values to 2D Array using C++ - php

I am building a neural net algorithm into C++ and using images for training data.
I need the data to be in an array of pixels represented by x,y|rgba values (A 2d array).
I have ImageMagick and the Magick++.h header plus compiler options all worked out.
I know the header library is working because I can :
int col = image.columns();
int row = image.rows();
cout << "COLS: " << col << "ROWS : " << row << endl;
My images are 32x32 and the result of the compiled program is:
root#jarvis:~/Documents/Programming/C++/ImageMagick# ./magick
COLS: 32 ROWS : 32
I just cannot seem to access the pixel values. I am not so fluent in C++ as I'd like but an example in PHP would be a function like this:
Function ImageToVector($Filename){
// open an image
$im = imagecreatefrompng($Filename);
$width = imagesx($im);
$height = imagesy($im);
$i = 0;
// get a color value for each pixle in width/height matrix
for ($x = 0; $x < $width; $x++){
for($y =0; $y < $height; $y++){
$color_index = imagecolorat($im,$x,$y);
// make it human readable and store it in the inputVector array.
//each pixel is read into the array one after the other making it a single inputVector
//later, we should know the dimensions of our input images (which should all be the same size in pixels).
//so we can lay it back down layer by layer if we wish to reconstruct the image from the rgba data in our input vectors later
$inputVector[$i] = imagecolorsforindex($im, $color_index);
$i++;
}
}
$color_tran = imagecolorsforindex($im, $color_index);
//return the input vector for entire image as an array
return ($inputVector);
}
$i=0;
$InputVector[$i] = ImageToVector("Example0.png");
My cpp file is this:
#include <iostream>
#include "/usr/include/ImageMagick/Magick++.h"
using namespace std;
using namespace Magick;
int main()
{
Image image("a.png");
int col = image.columns();
int row = image.rows();
PixelPacket *pixels = image.getPixels(0,0,col,row);
cout << "VALUE X: " << col << " ROWS : " << row << endl;
return 0;
}
My work around currently is to use the php function as is with a web form used to store the set of image data (input vectors) in a db. Then I can at least access that table from the C++ side.
I know how to do that much already. I was just kind of hoping for a more elegant solution on the import side. Thanks in advance everyone!
EDIT:
To access the pixel data I have tried things like
#include <iostream>
#include "/usr/include/ImageMagick/Magick++.h"
using namespace std;
using namespace Magick;
int main()
{
Image image("a.png");
int w = image.columns();
int h = image.rows();
PixelPacket *pixels = image.getPixels(0, 0, w, h);
int row = 0;
int column = 0;
Color color = pixels[w * row + column];
int x = pixels[0];
cout << "COLS: " << x << endl;
return 0;
}
or int x = pixels[0][0];
with either pixels[0][0] or pixels[0]
root#jarvis:~/Documents/Programming/C++/ImageMagick# ./compile_main.sh
main.cpp: In function âint main()â:
main.cpp:20:17: error: cannot convert âMagickCore::PixelPacket {aka MagickCore::_PixelPacket}â to âintâ in initialization
root#jarvis:~/Documents/Programming/C++/ImageMagick# ./compile_main.sh
main.cpp: In function âint main()â:
main.cpp:20:20: error: no match for âoperator[]â in â* pixels[0]â
root#jarvis:~/Documents/Programming/C++/ImageMagick#

I edited your code a bit, just to make it clear
#include <iostream>
#include "/usr/include/ImageMagick/Magick++.h"
using namespace std;
using namespace Magick;
int main()
{
Image image("a.png");
int w = image.columns();
int h = image.rows();
PixelPacket *pixels = image.getPixels(0, 0, w, h);
int row = 0;
int column = 0;
Color color = pixels[0]; // get first pixel color as an example
unsigned int red = color.redQuantum;
unsigned int blue = color.blueQuantum;
unsigned int green = color.greenQuantum;
unsigned int alpha = color.alphaQuantum;
cout << "RED:" << red << "BLUE:" << blue << "GREEN:" << green << "ALPHA:" << alpha << endl;
return 0;
}

#include <iostream>
#include "/usr/include/ImageMagick/Magick++.h"
using namespace std;
using namespace Magick;
int main()
{
Image image("a.png");
int w = image.columns();
int h = image.rows();
PixelPacket *pixels = image.getPixels(0, 0, w, h);
int row = 0;
int column = 0;
for(int i = 0; i < w*h; i++){
Color color = pixels[i]; // get first pixel color as an example
float red = color.redQuantum();
float blue = color.blueQuantum();
float green = color.greenQuantum();
float alpha = color.alphaQuantum();
//translate the bit value into standard rgba(255,255,255) values
if (red != 0){ red = red/256;} //if the (r)gba vector is 0, don't divide by 256
if (blue != 0){ blue = blue/256;} //if the r(g)ba vector is 0, don't divide by 256
if (green !=0) { green = green/256;}//if the rg(b)a vector is 0, don't divide by 256
if (alpha !=0) { alpha = alpha/256;}//if the rgb(a) vector is 0, don't divide by 256
//output red,green,blue values
cout << "R: " << red << " G: " << green << " B :" << blue << " A:" << alpha << endl;
}
return 0;
}
**edited for clearer output
example output:
R: 110.43 G: 110.43 B :110.43 A:0
R: 114.445 G: 114.445 B :114.445 A:0
R: 117.457 G: 118.461 B :118.461 A:0
R: 121.473 G: 121.473 B :122.477 A:0
R: 124.484 G: 125.488 B :125.488 A:0
R: 127.496 G: 128.5 B :128.5 A:0
R: 130.508 G: 130.508 B :130.508 A:0
Of course I will have to round those numbers to an int but thank you for your help here!

Related

Bit shifting in C is different from PHP

I have a question about a small piece of code in C to make the same piece of code work in PHP, it has to do with a bit shift and I can't figure out what's wrong.
C:
unsigned u = 3910796769;
u += u << 8;
printf("%u\n",u);
//Result : 52422369
PHP:
$u = 3910796769;
$u += $u << 8;
printf("%u\n",$u);
//Result : 1005074769633
Well, unsigned in C is 32bit, you cannot even shift the number you provided once without triggering an overflow, but you have shifted it 8 times and added one more time, like multiplying the number by 257, you should get the result mod 2^32 == 4294967296:
unsigned u = 3910796769;
u += u << 8;
this should be 256*u + u == 257 * u == 1005074769633 ~= 52422369 (mod 4294967296)
You can test it.
[...]
//Result : 52422369 /* correct (mod 2^32) */
PHP probably uses 64bit integers for the operations, and the result properly fits in 64bit.
$u = 3910796769;
$u += $u << 8;
printf("%u\n",$u);
//Result : 1005074769633
But if you try:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint64_t u = 3910796769;
u += u << 8;
printf("%Lu\n", u);
//Result : 1005074769633
}
you will get the correct result.
In my case, I needed to select elements from an array filled with 32-bit values using a specific formula.
The answer from #Eugene Sh helped me do this in PHP.
$u = 3910796769;
$u += $u << 8;
$u = $u & 0xFFFFFFFF
printf("%u\n",$u);
//Result : 52422369

removing / smoothing rough edges in gd library

I m using GD library to create images on the fly.
But when i rotate image using imagerotate() function
it works fine but it gives very much irritating rough edges of image
which is rotated.
as it is shown in this picture.
So how to make these sides/edges of rotated image smooth ?
One way to avoid from getting the Jaggies effect when rotating images is by using another way to sample the pixels than just taking the adjusted pixels, for example to use Nearest-neighbor interpolation to make the edges smoother. You can see matlab code example:
im1 = imread('lena.jpg');imshow(im1);
[m,n,p]=size(im1);
thet = rand(1);
mm = m*sqrt(2);
nn = n*sqrt(2);
for t=1:mm
for s=1:nn
i = uint16((t-mm/2)*cos(thet)+(s-nn/2)*sin(thet)+m/2);
j = uint16(-(t-mm/2)*sin(thet)+(s-nn/2)*cos(thet)+n/2);
if i>0 && j>0 && i<=m && j<=n
im2(t,s,:)=im1(i,j,:);
end
end
end
figure;
imshow(im2);
taken from (here). Basically it means that when sampling the pixels in the original picture, we sample near pixels and interpolate them to get the target pixel value. This way
you can achive waht you want withourt installing any additiional packages.
EDIT
I've found some old code I once wrote in Java, which contains implementations of a couple of sampling algorithems. Here is the code:
Nearest Neighbor sampler:
/**
* #pre (this!=null) && (this.pixels!=null)
* #post returns the sampled pixel of (x,y) by nearest neighbor sampling
*/
private Pixel sampleNearestNeighbor(double x, double y) {
int X = (int) Math.round(x);
int Y = (int) Math.round(y);
if (X >= 0 && Y >= 0 && X < this.pixels.length
&& Y < this.pixels[0].length)
// (X,Y) is within this.pixels' borders
return new Pixel(pixels[X][Y].getRGB());
else
return new Pixel(255, 255, 255);
// sample color will be default white
}
Bilinear sampler:
/**
* #pre (this!=null) && (this.pixels!=null)
* #post returns the sampled pixel of (x,y) by bilinear interpolation
*/
private Pixel sampleBilinear(double x, double y) {
int x1, y1, x2, y2;
x1 = (int) Math.floor(x);
y1 = (int) Math.floor(y);
double weightX = x - x1;
double weightY = y - y1;
if (x1 >= 0 && y1 >= 0 && x1 + 1 < this.pixels.length
&& y1 + 1 < this.pixels[0].length) {
x2 = x1 + 1;
y2 = y1 + 1;
double redAX = (weightX * this.pixels[x2][y1].getRed())
+ (1 - weightX) * this.pixels[x1][y1].getRed();
double greenAX = (weightX * this.pixels[x2][y1].getGreen())
+ (1 - weightX) * this.pixels[x1][y1].getGreen();
double blueAX = (weightX * this.pixels[x2][y1].getBlue())
+ (1 - weightX) * this.pixels[x1][y1].getBlue();
// bilinear interpolation of A point
double redBX = (weightX * this.pixels[x2][y2].getRed())
+ (1 - weightX) * this.pixels[x1][y2].getRed();
double greenBX = (weightX * this.pixels[x2][y2].getGreen())
+ (1 - weightX) * this.pixels[x1][y2].getGreen();
double blueBX = (weightX * this.pixels[x2][y2].getBlue())
+ (1 - weightX) * this.pixels[x1][y2].getBlue();
// bilinear interpolation of B point
int red = (int) (weightY * redBX + (1 - weightY) * redAX);
int green = (int) (weightY * greenBX + (1 - weightY) * greenAX);
int blue = (int) (weightY * blueBX + (1 - weightY) * blueAX);
// bilinear interpolation of A and B
return new Pixel(red, green, blue);
} else if (x1 >= 0
&& y1 >= 0 // last row or column
&& (x1 == this.pixels.length - 1 || y1 == this.pixels[0].length - 1)) {
return new Pixel(this.pixels[x1][y1].getRed(), this.pixels[x1][y1]
.getGreen(), this.pixels[x1][y1].getBlue());
} else
return new Pixel(255, 255, 255);
// sample color will be default white
}
Gaussian sampler:
/**
* #pre (this!=null) && (this.pixels!=null)
* #post returns the sampled pixel of (x,y) by gaussian function
*/
private Pixel sampleGaussian(double u, double v) {
double w = 3; // sampling distance
double sqrSigma = Math.pow(w / 3.0, 2); // sigma^2
double normal = 0;
double red = 0, green = 0, blue = 0;
double minIX = Math.round(u - w);
double maxIX = Math.round(u + w);
double minIY = Math.round(v - w);
double maxIY = Math.round(v + w);
for (int ix = (int) minIX; ix <= maxIX; ix++) {
for (int iy = (int) minIY; iy <= maxIY; iy++) {
double sqrD = Math.pow(ix - u, 2) + Math.pow(iy - v, 2);
// squared distance between (ix,iy) and (u,v)
if (sqrD < Math.pow(w, 2) && ix >= 0 && iy >= 0
&& ix < pixels.length && iy < pixels[0].length) {
// gaussian function
double gaussianWeight = Math.pow(2, -1 * (sqrD / sqrSigma));
normal += gaussianWeight;
red += gaussianWeight * pixels[ix][iy].getRed();
green += gaussianWeight * pixels[ix][iy].getGreen();
blue += gaussianWeight * pixels[ix][iy].getBlue();
}
}
}
red /= normal;
green /= normal;
blue /= normal;
return new Pixel(red, green, blue);
}
Actual rotate:
/**
* #pre (this!=null) && (this.pixels!=null) && (1 <= samplingMethod <= 3)
* #post creates a new rotated-by-degrees Image and returns it
*/
public myImage rotate(double degrees, int samplingMethod) {
myImage outputImg = null;
int t = 0;
for (; degrees < 0 || degrees >= 180; degrees += (degrees < 0) ? 180
: -180)
t++;
int w = this.pixels.length;
int h = this.pixels[0].length;
double cosinus = Math.cos(Math.toRadians(degrees));
double sinus = Math.sin(Math.toRadians(degrees));
int width = Math.round((float) (w * Math.abs(cosinus) + h * sinus));
int height = Math.round((float) (h * Math.abs(cosinus) + w * sinus));
w--;
h--; // move from (1,..,k) to (0,..,1-k)
Pixel[][] pixelsArray = new Pixel[width][height];
double x = 0; // x coordinate in the source image
double y = 0; // y coordinate in the source image
if (degrees >= 90) { // // 270 or 90 degrees turn
double temp = cosinus;
cosinus = sinus;
sinus = -temp;
}
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
double x0 = i;
double y0 = j;
if (degrees >= 90) {
if ((t % 2 == 1)) { // 270 degrees turn
x0 = j;
y0 = width - i - 1;
} else { // 90 degrees turn
x0 = height - j - 1;
y0 = i;
}
} else if (t % 2 == 1) { // 180 degrees turn
x0 = width - x0 - 1;
y0 = height - y0 - 1;
}
// calculate new x/y coordinates and
// adjust their locations to the middle of the picture
x = x0 * cosinus - (y0 - sinus * w) * sinus;
y = x0 * sinus + (y0 - sinus * w) * cosinus;
if (x < -0.5 || x > w + 0.5 || y < -0.5 || y > h + 0.5)
// the pixels that does not have a source will be painted in
// default white
pixelsArray[i][j] = new Pixel(255, 255, 255);
else {
if (samplingMethod == 1)
pixelsArray[i][j] = sampleNearestNeighbor(x, y);
else if (samplingMethod == 2)
pixelsArray[i][j] = sampleBilinear(x, y);
else if (samplingMethod == 3)
pixelsArray[i][j] = sampleGaussian(x, y);
}
}
outputImg = new myImage(pixelsArray);
}
return outputImg;
}
It may sound rather hack-ish, but it is the simplest way to do it, and even big enterprise solutions use this.
The trick is to first create the image 2X the size of what you need, then do all the drawing calls and then resize it to required original size.
Not only it is really easy to do, but also it is as fast as it gets and it produces very nice results. I use this trick for all cases when I need to apply blur to edges.
Another advantate to this is that it does not include blur on the rest of the image and it remains crisp clear - only borders of rotated image gets smoothed.
One thing you could try is to use imageantialias() to smooth the edges.
If that doesn't suit your needs, GD itself will probably not suffice.
GD uses very fast methods for all it's abilites without any actual smoothing or anything like that involved. If you want some proper image editing, you could either look into ImageMagick (which requires extra-software on the server) or write your own functions based on GD.
Keep in mind though, that php is really slow with huge amounts of data, so writing your own functions might be disappointing. (From my experience, PHP is roughly 40 times slower than compiled code.)
I recommend using ImageMagick for any image work where result quality matters.

How to convert REAL48 float into a double

I am connecting to a Pervasive SQL database which splits some data over two fields. DOUBLE fields are actually split into fieldName_1 and fieldName_2 where _1 is a 2 byte int and _2 is a 4 byte int.
I want to take these values and convert them using PHP into a usable value.
I have some example code to do the conversion, but it is written in Delphi which I do not understand:
{ Reconstitutes a SmallInt and LongInt that form }
{ a Real into a double. }
Function EntConvertInts (Const Int2 : SmallInt;
Const Int4 : LongInt) : Double; StdCall;
Var
TheRealArray : Array [1..6] Of Char;
TheReal : Real;
Begin
Move (Int2, TheRealArray[1], 2);
Move (Int4, TheRealArray[3], 4);
Move (TheRealArray[1], TheReal, 6);
Result := TheReal;
End;
Some data [fieldName_1,fieldName_2]
[132, 805306368] -> this should be 11
[132, 1073741824] -> this should be 12
I don't understand the logic enough to be able to port this into PHP. Any help would be most appreciated. Thanks
EDIT.
This is the C code that they provided, showing sign/exponent:
double real_to_double (real r)
/* takes Pascal real, return C double */
{
union doublearray da;
unsigned x;
x = r[0] & 0x00FF; /* Real biased exponent in x */
/* when exponent is 0, value is 0.0 */
if (x == 0)
da.d = 0.0;
else {
da.a[3] = ((x + 894) << 4) | /* adjust exponent bias */
(r[2] & 0x8000) | /* sign bit */
((r[2] & 0x7800) >> 11); /* begin significand */
da.a[2] = (r[2] << 5) | /* continue shifting significand */
(r[1] >> 11);
da.a[1] = (r[1] << 5) |
(r[0] >> 11);
da.a[0] = (r[0] & 0xFF00) << 5; /* mask real's exponent */
}
return da.d;
}
Adding this as another answer because I've finally figured this out. Here is PHP code which will convert the values. It has to be manually calculated because PHP does not know how to unpack a Real48 (non standard). Explanation in comments below.
function BiIntToReal48($f1, $f2){
$x = str_pad(decbin($f1), 16, "0", STR_PAD_LEFT);
$y = str_pad(decbin($f2), 32, "0", STR_PAD_LEFT);
//full Real48 binary string
$real48 = $y . $x;
//Real48 format is V = (-1)^s * 1.f * 2^(exp-129)
// rightmost eight bits are the exponent (bits 40-->47)
// subtract 129 to get the final value
$exp = (bindec(substr($real48, -8)) - 129);
//Sign bit is leftmost bit (bit[0])
$sign =$real48[0];
//Now work through the significand - bits are fractional binary
//(1/2s place, 1/4s place, 1/8ths place, etc)
// bits 1-->39
// significand is always 1.fffffffff... etc so start with 1.0
$sgf = "1.0";
for ($i = 1; $i <= 39; $i++){
if ($real48[$i] == 1){
$sgf = $sgf + pow(2,-$i);
}
}
//final calculation
$final = pow(-1, $sign) * $sgf * pow(2,$exp);
return($final);
}
$field_1 = 132;
$field_2 = 805306368;
$ConvVal = BiIntToReal48($field_1, $field_2);
// ^ gives $ConvVal = 11, qed
I've been working on this issue for about a week now trying to get it sorted out for our organisation.
Our Finance dept use IRIS Exchequer and we need to get costs out. Using the above PHP code, I managed to get it working in Excel VBA with the following code (includes dependent functions). If not properly attributed below, I got all the long dec to bin functions from www.sulprobil.com. If you copy and paste the following code block into a Module you can reference my ExchequerDouble function from a cell.
Before I continue, I have to point out one error in the C/PHP code above. If you look at the Significand loops:
C/PHP: Significand = Significand + 2 ^ (-i)
VBA: Significand = Significand + 2 ^ (1 - i)
I noticed during testing that the answers were very close but often incorrect. Drilling further down I narrowed it down to the Significand. It might be a problem with translating the code from one language/methodology to another, or may have simply been a typo, but adding that (1 - i) made all the difference.
Function ExchequerDouble(Val1 As Integer, Val2 As Long) As Double
Dim Int2 As String
Dim Int4 As String
Dim Real48 As String
Dim Exponent As String
Dim Sign As String
Dim Significand As String
'Convert each value to binary
Int2 = LongDec2Bin(Val1, 16, True)
Int4 = LongDec2Bin(Val2, 32, True)
'Concatenate the binary strings to produce a 48 bit "Real"
Real48 = Int4 & Int2
'Calculate the exponent
Exponent = LongBin2Dec(Right(Real48, 8)) - 129
'Calculate the sign
Sign = Left(Real48, 1)
'Begin calculation of Significand
Significand = "1.0"
For i = 2 To 40
If Mid(Real48, i, 1) = "1" Then
Significand = Significand + 2 ^ (1 - i)
End If
Next i
ExchequerDouble = CDbl(((-1) ^ Sign) * Significand * (2 ^ Exponent))
End Function
Function LongDec2Bin(ByVal sDecimal As String, Optional lBits As Long = 32, Optional blZeroize As Boolean = False) As String
'Transforms decimal number into binary number.
'Reverse("moc.LiborPlus.www") V0.3 P3 16-Jan-2011
Dim sDec As String
Dim sFrac As String
Dim sD As String 'Internal temp variable to represent decimal
Dim sB As String
Dim blNeg As Boolean
Dim i As Long
Dim lPosDec As Long
Dim lLenBinInt As Long
lPosDec = InStr(sDecimal, Application.DecimalSeparator)
If lPosDec > 0 Then
If Left(sDecimal, 1) = "-" Then 'negative fractions later..
LongDec2Bin = CVErr(xlErrValue)
Exit Function
End If
sDec = Left(sDecimal, lPosDec - 1)
sFrac = Right(sDecimal, Len(sDecimal) - lPosDec)
lPosDec = Len(sFrac)
Else
sDec = sDecimal
sFrac = ""
End If
sB = ""
If Left(sDec, 1) = "-" Then
blNeg = True
sD = Right(sDec, Len(sDec) - 1)
Else
blNeg = False
sD = sDec
End If
Do While Len(sD) > 0
Select Case Right(sD, 1)
Case "0", "2", "4", "6", "8"
sB = "0" & sB
Case "1", "3", "5", "7", "9"
sB = "1" & sB
Case Else
LongDec2Bin = CVErr(xlErrValue)
Exit Function
End Select
sD = sbDivBy2(sD, True)
If sD = "0" Then
Exit Do
End If
Loop
If blNeg And sB <> "1" & String(lBits - 1, "0") Then
sB = sbBinNeg(sB, lBits)
End If
'Test whether string representation is in range and correct
'If not, the user has to increase lbits
lLenBinInt = Len(sB)
If lLenBinInt > lBits Then
LongDec2Bin = CVErr(x1ErrNum)
Exit Function
Else
If (Len(sB) = lBits) And (Left(sB, 1) <> -blNeg & "") Then
LongDec2Bin = CVErr(xlErrNum)
Exit Function
End If
End If
If blZeroize Then sB = Right(String(lBits, "0") & sB, lBits)
If lPosDec > 0 And lLenBinInt + 1 < lBits Then
sB = sB & Application.DecimalSeparator
i = 1
Do While i + lLenBinInt < lBits
sFrac = sbDecAdd(sFrac, sFrac) 'Double fractional part
If Len(sFrac) > lPosDec Then
sB = sB & "1"
sFrac = Right(sFrac, lPosDec)
If sFrac = String(lPosDec, "0") Then
Exit Do
End If
Else
sB = sB & "0"
End If
i = i + 1
Loop
LongDec2Bin = sB
Else
LongDec2Bin = sB
End If
End Function
Function LongBin2Dec(sBinary As String, Optional lBits As Long = 32) As String
'Transforms binary number into decimal number.
'Reverse("moc.LiborPlus.www") V0.3 PB 16-Jan-2011
Dim sBin As String
Dim sB As String
Dim sFrac As String
Dim sD As String
Dim sR As String
Dim blNeg As Boolean
Dim i As Long
Dim lPosDec As Long
lPosDec = InStr(sBinary, Application.DecimalSeparator)
If lPosDec > 0 Then
If (Left(sBinary, 1) = "1") And Len(sBin) >= lBits Then 'negative fractions later..
LongBin2Dec = CVErr(xlErrVa1ue)
Exit Function
End If
sBin = Left(sBinary, lPosDec - 1)
sFrac = Right(sBinary, Len(sBinary) - lPosDec)
lPosDec = Len(sFrac)
Else
sBin = sBinary
sFrac = ""
End If
Select Case Sgn(Len(sBin) - lBits)
Case 1
LongBin2Dec = CVErr(x1ErrNum)
Exit Function
Case 0
If Left(sBin, 1) = "1" Then
sB = sbBinNeg(sBin, lBits)
blNeg = True
Else
sB = sBin
blNeg = False
End If
Case -1
sB = sBin
blNeg = False
End Select
sD = "1"
sR = "0"
For i = Len(sB) To 1 Step -1
Select Case Mid(sB, i, 1)
Case "1"
sR = sbDecAdd(sR, sD)
Case "0"
'Do Nothing
Case Else
LongBin2Dec = CVErr(xlErrNum)
Exit Function
End Select
sD = sbDecAdd(sD, sD) 'Double sd
Next i
If lPosDec > 0 Then 'now the fraction
sD = "0.5"
For i = 1 To lPosDec
If Mid(sFrac, i, 1) = "1" Then
sR = sbDecAdd(sR, sD)
End If
sD = sbDivBy2(sD, False)
Next i
End If
If blNeg Then
LongBin2Dec = "-" & sR
Else
LongBin2Dec = sR
End If
End Function
Function sbDivBy2(sDecimal As String, blInt As Boolean) As String
'Divide sDecimal by two, blInt = TRUE returns integer only
'Reverse("moc.LiborPlus.www") V0.3 PB 16-Jan-2011
Dim i As Long
Dim lPosDec As Long
Dim sDec As String
Dim sD As String
Dim lCarry As Long
If Not blInt Then
lPosDec = InStr(sDecimal, Application.DecimalSeparator)
If lPosDec > 0 Then
'Without decimal point lPosDec already defines location of decimal point
sDec = Left(sDecimal, lPosDec - 1) & Right(sDecimal, Len(sDecimal) - lPosDec)
Else
sDec = sDecimal
lPosDec = Len(sDec) + 1 'Location of decimal point
End If
If ((1 * Right(sDec, 1)) Mod 2) = 1 Then
sDec = sDec & "0" 'Append zero so that integer algorithm calculates division exactly
End If
Else
sDec = sDecimal
End If
lCarry = 0
For i = 1 To Len(sDec)
sD = sD & Int((lCarry * 10 + Mid(sDec, i, 1)) / 2)
lCarry = (lCarry * 10 + Mid(sDec, i, 1)) Mod 2
Next i
If Not blInt Then
If Right(sD, Len(sD) - lPosDec + 1) <> String(Len(sD) - lPosDec + 1, "0") Then
'frac part Is non - zero
i = Len(sD)
Do While Mid(sD, i, 1) = "0"
i = i - 1 'Skip trailing zeros
Loop
'Insert decimal point again
sD = Left(sD, lPosDec - 1) _
& Application.DecimalSeparator & Mid(sD, lPosDec, i - lPosDec + 1)
End If
End If
i = 1
Do While i < Len(sD)
If Mid(sD, i, 1) = "0" Then
i = i + 1
Else
Exit Do
End If
Loop
If Mid(sD, i, 1) = Application.DecimalSeparator Then
i = i - 1
End If
sbDivBy2 = Right(sD, Len(sD) - i + 1)
End Function
Function sbBinNeg(sBin As String, Optional lBits As Long = 32) As String
'Negate sBin: take the 2's-complement, then add one
'Reverse("moc.LiborPlus.www") V0.3 PB 16-Jan-2011
Dim i As Long
Dim sB As String
If Len(sBin) > lBits Or sBin = "1" & String(lBits - 1, "0") Then
sbBinNeg = CVErr(xlErrValue)
Exit Function
End If
'Calculate 2 's-complement
For i = Len(sBin) To 1 Step -1
Select Case Mid(sBin, i, 1)
Case "1"
sB = "0" & sB
Case "0"
sB = "1" & sB
Case Else
sbBinNeg = CVErr(xlErrValue)
Exit Function
End Select
Next i
sB = String(lBits - Len(sBin), "1") & sB
'Now add 1
i = lBits
Do While i > 0
If Mid(sB, i, 1) = "1" Then
Mid(sB, i, 1) = "0"
i = i - 1
Else
Mid(sB, i, 1) = "1"
i = 0
End If
Loop
'Finally strip leading zeros
i = InStr(sB, "1")
If i = 0 Then
sbBinNeg = "0"
Else
sbBinNeg = Right(sB, Len(sB) - i + 1)
End If
End Function
Function sbDecAdd(sOne As String, sTwo As String) As String
'Sum up two string decimals.
'Reverse("moc.LiborPlus.www") V0.3 PB 16-Jan-2011
Dim lStrLen As Long
Dim s1 As String
Dim s2 As String
Dim sA As String
Dim sB As String
Dim sR As String
Dim d As Long
Dim lCarry As Long
Dim lPosDec1 As Long
Dim lPosDec2 As Long
Dim sF1 As String
Dim sF2 As String
lPosDec1 = InStr(sOne, Application.DecimalSeparator)
If lPosDec1 > 0 Then
s1 = Left(sOne, lPosDec1 - 1)
sF1 = Right(sOne, Len(sOne) - lPosDec1)
lPosDec1 = Len(sF1)
Else
s1 = sOne
sF1 = ""
End If
lPosDec2 = InStr(sTwo, Application.DecimalSeparator)
If lPosDec2 > 0 Then
s2 = Left(sTwo, lPosDec2 - 1)
sF2 = Right(sTwo, Len(sTwo) - lPosDec2)
lPosDec2 = Len(sF2)
Else
s2 = sTwo
sF2 = ""
End If
If lPosDec1 + lPosDec2 > 0 Then
If lPosDecl > lPosDec2 Then
sF2 = sF2 & String(lPosDec1 - lPosDec2, "0")
Else
sF1 = sFl & String(lPosDec2 - lPosDec1, "0")
lPosDec1 = lPosDec2
End If
sF1 = sbDecAdd(sF1, sF2) 'Add fractions as integer numbers
If Len(sF1) > lPosDecl Then
lCarry = 1
sF1 = Right(sF1, lPosDec1)
Else
lCarry = 0
End If
Do While lPosDec1 > 0
If Mid(sF1, lPosDec1, 1) <> "0" Then
Exit Do
End If
lPosDec1 = lPosDec1 - 1
Loop
sF1 = Left(sF1, lPosDec1)
Else
lCarry = 0
End If
lStrLen = Len(sl)
If lStrLen < Len(s2) Then
lStrLen = Len(s2)
sA = String(lStrLen - Len(s1), "0") & s1
sB = s2
Else
sA = s1
sB = String(lStrLen - Len(s2), "0") & s2
End If
Do While lStrLen > 0
d = 0 + Mid(sA, lStrLen, 1) + Mid(sB, lStrLen, 1) + lCarry
If d > 9 Then
sR = (d - 10) & sR
lCarry = 1
Else
sR = d & sR
lCarry = 0
End If
lStrLen = lStrLen - 1
Loop
If lCarry > 0 Then
sR = lCarry & sR
End If
If lPosDec1 > 0 Then
sbDecAdd = sR & Application.DecimalSeparator & sF1
Else
sbDecAdd = sR
End If
End Function
This code works, but sometimes (around 1% of my test data) you end up a couple pennies out compared to Iris' EntDouble function from the Excel Addin. I'll attribute this to precision, unless someone can figure it out.
Ultimately getting this working in VBA was my proof of concept to check everything worked. The intended platform for this functionality was SQL Server. If you have your Exchequer DB linked to a SQL Server you should be able to run this function directly against the data from the Pervasive DB. In my case, we are going to dump out the last 2.5 years worth of transaction data into a static table on SQL Server, but we're only working with this data once a year so it's not an issue. The following two functions should sort you out. In terms of precision, they are equivalent to the VBA code above with some being out by a couple pennies sometimes, but it seems 99% of the time it's exactly the same. We use SQL Server 2000 so there are some things that can probably be optimised (Varchar(MAX) for one) for newer versions but ultimately this should work fine as far as I know.
CREATE FUNCTION dbo.FUNCTION_Exchequer_Double
(
#Val1 AS SmallInt,
#Val2 AS BigInt
)
RETURNS Decimal(38, 10)
AS
BEGIN
-- Declare and set decoy variables
DECLARE #Val1_Decoy AS SmallInt
DECLARE #Val2_Decoy AS BigInt
SELECT #Val1_Decoy = #Val1,
#Val2_Decoy = #Val2
-- Declare other variables
DECLARE #Val1_Binary AS Varchar(16)
DECLARE #Val2_Binary AS Varchar(32)
DECLARE #Real48_Binary AS Varchar(48)
DECLARE #Real48_Decimal AS BigInt
DECLARE #Exponent AS Int
DECLARE #Sign AS Bit
DECLARE #Significand AS Decimal(19, 10)
DECLARE #BitCounter AS Int
DECLARE #Two As Decimal(38, 10) -- Saves us casting inline in the code
DECLARE #Output AS Decimal(38, 10)
-- Convert values into two binary strings of the correct length (Val1 = 16 bits, Val2 = 32 bits)
SELECT #Val1_Binary = Replicate(0, 16 - Len(dbo.FUNCTION_Convert_To_Base(Cast(#Val1_Decoy AS Binary(2)), 2)))
+ dbo.FUNCTION_Convert_To_Base(Cast(#Val1_Decoy AS Binary(2)), 2),
#Val2_Binary = Replicate(0, 32 - Len(dbo.FUNCTION_Convert_To_Base(Cast(#Val2_Decoy AS Binary(4)), 2)))
+ dbo.FUNCTION_Convert_To_Base(Cast(#Val2_Decoy AS Binary(4)), 2)
-- Find the decimal value of the new 48 bit number and its binary value
SELECT #Real48_Decimal = #Val2_Decoy * Power(2, 16) + #Val1_Decoy
SELECT #Real48_Binary = #Val2_Binary + #Val1_Binary
-- Determine the Exponent (takes the first 8 bits and subtracts 129)
SELECT #Exponent = Cast(#Real48_Decimal AS Binary(1)) - 129
-- Determine the Sign
SELECT #Sign = Left(#Real48_Binary, 1)
-- A bit of setup for determining the Significand
SELECT #Significand = 1,
#Two = 2,
#BitCounter = 2
-- Determine the Significand
WHILE #BitCounter <= 40
BEGIN
IF Substring(#Real48_Binary, #BitCounter, 1) Like '1'
BEGIN
SELECT #Significand = #Significand + Power(#Two, 1 - #BitCounter)
END
SELECT #BitCounter = #BitCounter + 1
END
SELECT #Output = Power(-1, #Sign) * #Significand * Power(#Two, #Exponent)
-- Return the output
RETURN #Output
END
CREATE FUNCTION dbo.FUNCTION_Convert_To_Base
(
#value AS BigInt,
#base AS Int
)
RETURNS Varchar(8000)
AS
BEGIN
-- Code from http://dpatrickcaldwell.blogspot.co.uk/2009/05/converting-decimal-to-hexadecimal-with.html
-- some variables
DECLARE #characters Char(36)
DECLARE #result Varchar(8000)
-- the encoding string and the default result
SELECT #characters = '0123456789abcdefghijklmnopqrstuvwxyz',
#result = ''
-- make sure it's something we can encode. you can't have
-- base 1, but if we extended the length of our #character
-- string, we could have greater than base 36
IF #value < 0 Or #base < 2 Or #base > 36
RETURN Null
-- until the value is completely converted, get the modulus
-- of the value and prepend it to the result string. then
-- devide the value by the base and truncate the remainder
WHILE #value > 0
SELECT #result = Substring(#characters, #value % #base + 1, 1) + #result,
#value = #value / #base
-- return our results
RETURN #result
END
Feel free to use either my VBA or SQL code. The truly hard work was done by whoever converted it to PHP above. If anyone finds any way of improving anything please do let me know so we can make this code as perfect as possible.
Thanks!
Delphi's Move command is used for moving blocks of memory from one place to another. This looks like old Delphi code - the Real type is obsolete, replaced with Double (edit Real48 replaces 6-byte Real), and the Byte type is probably a better one to use than Char. Both are bytes, but Char is more meant for single byte characters (ascii). What this code is doing is:
1) Declare an array of Char(could use Byte here) which is six bytes in length. Also declare a Real (edit now Real48 type) to store the converted value.
TheRealArray : Array [1..6] Of Char;
TheReal : Real;
2) Move the two-byte Int value TO TheRealArray - start at index1 and move 2 bytes of data (ie: all of Int2, a SmallInt (16-bits)). Do the same with Int4 and start it at index [3], 4 bytes long.
Move (Int2, TheRealArray[1], 2);
Move (Int4, TheRealArray[3], 4);
if you started with (picture, not code)
Int2 = [2_byte0][2_byte1]
Int4 = [4_byte0][4_byte1][4_byte2][4_byte3]
you would have:
TheRealArray = [2_byte0][2_byte1][4_byte0][4_byte1][4_byte2][4_byte3]
The final move command copies this array to the memory location of TheReal, which is a real (6-byte float) type. It starts at index1 of the array, copies it to TheReal, and copies a total of six bytes (ie:the whole thing).
Move (TheRealArray[1], TheReal, 6);
Assuming that the data stored in Int2 and Int4, when concatenated like this, produce a properly formatted Real48 then you end up with TheReal holding the data in the proper format.
in PHP strings are fundamentally byte arrays (like Array[1..6] of Char in Delphi) so you could do the something similar using unpack() to convert to float.
Just spinning on J...'s answer.
Utilizing a variant record the code is somewhat simplified :
Function EntConvertInts (Const Int2 : SmallInt;
Const Int4 : LongInt) : Double; StdCall;
Type
TReal48PlaceHolder = record
case boolean of
true : (theRealArray : array [1..6] of byte);
false : (r48 : Real48);
end;
Var
R48Rec : TReal48PlaceHolder;
Begin
Move (Int2, R48Rec.theRealArray[1], 2);
Move (Int4, R48Rec.theRealArray[3], 4);
Result := R48Rec.r48;
End;
var
r : Double;
begin
r:= EntConvertInts(132,805306368);
WriteLn(r); // Should be 11
r:= EntConvertInts(141,1163395072);
WriteLn(r); // Should be 6315
ReadLn;
end.
That is nor answer in "PHP code" sense. I just wanted to warn any person who maybe would find this code by Delphi tag.
THAT WAS NOT DELPHI !!!
It is old Turbo Pascal code. Okay, maybe 16-bit Delphi 1, which really was TP on steroids.
Don't try this code on 32-bit Delphi, at least not before replacing Char and Real types that changed. Both those types are changed from Turbo Pascal times, especially 6-byte Real which never was hardware FPU-compatible!
Probably FreePascal can bear vanilla TurboPascal code if settled to proper mode, but better still use Delphi mode and updated code.
http://docwiki.embarcadero.com/Libraries/en/System.Real
http://docwiki.embarcadero.com/Libraries/en/System.Real48
http://docwiki.embarcadero.com/RADStudio/en/Real48_compatibility_(Delphi)
One should also ensure that SmallInt type is 16-bit integer (int16) and LongInt is 32-bit(int32). This seemes to hold for 16-bit, 32-bit and 64-bit Delphi compilers, yet probably may change in other Pascal implementations.
http://docwiki.embarcadero.com/Libraries/en/System.Longint
http://docwiki.embarcadero.com/Libraries/en/System.Smallint
Below i try to modify code compatible with modern Delphi. I was not able to test it though.
Hopefully that might help someone someday covert some similat old type-casting TurboPascal code to newer flavours.
This code is directly following original one, yet more compatible, concise and fast.
{ Reconstitutes a SmallInt and LongInt that form }
{ a Real into a double. }
Function EntConvertInts (Const Int2 : SmallInt;
Const Int4 : LongInt) : Double;
(* StdCall; - only needed for non-Pascal DLLs *)
Var
TheRealArray : Packed Array [1..6] Of Byte; //AnsiChar may suffice too
TheReal : Real48 absolute TheRealArray;
TheInt2 : SmallInt absolute TheRealArray[1];
TheInt4 : LongInt absolute TheRealArray[3];
Begin
Assert(SizeOf(TheInt2) = 2);
Assert(SizeOf(TheInt4) = 2);
Assert(SizeOf(TheReal) = 6);
TheInt2 := Int2; (* Move (Int2, TheRealArray[1], 2); *)
TheInt4 := Int4; (* Move (Int4, TheRealArray[3], 4); *)
(* Move (TheRealArray[1], TheReal, 6); *)
Result := TheReal;
End;
This code is directly using native Turbo Pascal features tagless variant record
{ Reconstitutes a SmallInt and LongInt that form }
{ a Real into a double. }
Function EntConvertInts (Const Int2 : SmallInt;
Const Int4 : LongInt) : Double;
(* StdCall; - only needed for non-Pascal DLLs *)
Var
Value : Packed Record
Case Byte of
0: (TheReal: Real48);
1: (Packed Record TheInt2: SmallInt;
TheInt4: LongInt; end; );
end;
Begin
Assert(SizeOf(Value.TheInt2) = 2);
Assert(SizeOf(Value.TheInt4) = 2);
Assert(SizeOf(Value.TheReal) = 6);
Value.TheInt2 := Int2; (* Move (Int2, TheRealArray[1], 2); *)
Value.TheInt4 := Int4; (* Move (Int4, TheRealArray[3], 4); *)
(* Move (TheRealArray[1], TheReal, 6); *)
Result := Value.TheReal;
End;

Implement a function calculating the number of positive integers up to and including n divisible by at least one of the primes in a given array

I do not really know c + +, but I need to translate the algorithm in php. Could you help me, especially not clear line std:: transform (...
task is:
Implement a function calculating the number of positive integers up to and including n divisible by at least one of the primes in a given array. The caller will ensure that this array is sorted and only contains unique primes, so your implementation may take advantage of these assumptions and doesn't need to
check whether they actually hold true.
There is a very efficient algorithm for counting these numbers for any values of n, as long as the list of divisors remains relatively short.
#include <algorithm>
#include <functional>
#include <iostream>
#include <ostream>
#include <vector>
std::vector<signed int> gen_products_of_n_divisors(
const std::vector<signed int>::const_iterator &start,
const std::vector<signed int>::const_iterator &end,
signed int n)
{
if (n == 1)
{
return std::vector<signed int>(start, end);
}
std::vector<signed int> products;
for (std::vector<signed int>::const_iterator i = start;
i != end; ++i)
{
std::vector<signed int> sub_products =
gen_products_of_n_divisors(i + 1, end, n - 1);
products.resize(products.size() + sub_products.size());
std::transform(sub_products.begin(), sub_products.end(),
products.end() - sub_products.size(),
std::bind1st(std::multiplies<signed int>(), *i));
}
return std::vector<signed int>(products);
}
signed int count_divisibles(signed int n,
const std::vector<signed int> &divisors)
{
signed int total_count = 0;
for (signed int i = 1;
i <= static_cast<signed int>(divisors.size()); ++i)
{
std::vector<signed int> products =
gen_products_of_n_divisors(divisors.begin(),
divisors.end(), i);
signed int sign = 2 * (i % 2) - 1;
for (
std::vector<signed int>::iterator j =
products.begin();
j != products.end(); ++j)
{
total_count += sign * n / (*j);
}
}
return total_count;
}
int main()
{
std::vector<signed int> a;
a.push_back(3);
a.push_back(5);
a.push_back(7);
a.push_back(11);
a.push_back(13);
a.push_back(17);
a.push_back(19);
std::cout << count_divisibles(1000000, a) << std::endl;
}
It will be easier to understand Toolbox's std::transform reference and his or her explanation of how sub-products (products of members of subsets of the set of divisors) are formed, if you are familiar with the Inclusion–exclusion principle. In effect, sub-products that are products of an odd number of numbers add to the total number of divisors, while those that are products of an even number of numbers subtract from it. This may be more obvious in the following translation to C of the C++ program in question.
In the program, note that 1<<nDiv is 2^nDiv (with ^ denoting exponentiation here). There are 2^k subsets in the power set of a set of k elements. Each distinct subset corresponds to a distinct binary ID#. (ID#="identity number"). A set element is a member of a subset if the bit for that element is set in the ID# of the subset. The program toggles sign from -1 to 1 or from 1 to -1 to keep track of even or odd number of bits.
A real program (vs a toy demo like this) should check for overflow when it computes product in the innermost loop of count_divisibles().
// translation to C of C++ program in question
#include <stdlib.h>
#include <stdio.h>
int count_divisibles(int n, int *divisors, int nDiv) {
int total_count = 0;
int i, it, j, sign, product;
for (i=1; i < 1<<nDiv; ++i) {
product = 1;
sign = -1;
for (j=0, it=i; j<nDiv; ++j, it=it/2) {
if (it & 1) {
product *= divisors[j];
sign = -sign;
}
}
total_count += sign * n/product;
}
return total_count;
}
int main(void) {
int a[] = {3,5,7,11,13,17};
int nDiv = sizeof a / sizeof a[0];
int hi, c, k;
for (hi=1000000; hi; hi/=200) {
for (k=0; k<nDiv; ++k) {
c = count_divisibles(hi, a, k);
printf ("count_divisibles(%d, a, %d) = %6d a[%d]=%d\n",
hi, k, c, k, a[k]);
}
c = count_divisibles(hi, a, nDiv);
printf ("count_divisibles(%d, a, %d) = %6d\n", hi, nDiv, c);
}
return 0;
}

Javascript crc32 function and PHP crc32 not matching

I'm working on a webapp where I want to match some crc32 values that have been generated server side in PHP with some crc32 values that I am generating in Javascript. Both are using the same input string but returning different values.
I found a crc32 javascript library on webtoolkit, found here. When I try and match a simple CRC32 value that I generate in PHP, for the life of me I can't generate the same matching value in the Javascript crc32 function. I tried adding a utf-8 language encoding meta tag to the top of my page with no luck. I've also tried adding a PHP utf8_encode() around the string before I enter it into the PHP crc32 function, but still no matching crc's ....
Is this a character encoding issue? How do I get these two generated crc's to match? Thanks everyone!
/**
*
* Javascript crc32
* http://www.webtoolkit.info/
*
**/
function crc32 (str) {
function Utf8Encode(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
str = Utf8Encode(str);
var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
if (typeof(crc) == "undefined") { crc = 0; }
var x = 0;
var y = 0;
crc = crc ^ (-1);
for( var i = 0, iTop = str.length; i < iTop; i++ ) {
y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
x = "0x" + table.substr( y * 9, 8 );
crc = ( crc >>> 8 ) ^ x;
}
return crc ^ (-1);
};
I actually needed this exact same functionality recently for a work project. So this is what I have been able to figure out.
The reason they do not match is because the Javascript implementation is not working on bytes. Using str.charCodeAt(i) will not always return a value 0-255 (in the case of Unicode characters it'll return a potentially much larger number). The Utf8Encode function might be trying to work around this but I don't think it will work for any given binary data.
Using the stringToBytes function from this question: Reading bytes from a JavaScript string will help convert data in a string to bytes. Though I did experience some completely dropped bytes, which seemed more to do with how the string was being stored in the browser than the function itself, it may work in your situation however.
One other hiccup you might have is that PHP's crc32 function will return an unsigned 32bit integer. The above function will return a signed 32bit integer. So given those two things here is the function I ended up with:
crc32 = {
table:"00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D",
//This will probably match php's crc32
genBytes:function(str, crc ) {
var bytes = stringToBytes(str)
if( crc == window.undefined ) crc = 0;
var n = 0; //a number between 0 and 255
var x = 0; //a hex number
crc = crc ^ (-1);
for( var i = 0, iTop = bytes.length; i < iTop; i++ ) {
n = ( crc ^ bytes[i] ) & 0xFF;
x = "0x" + this.table.substr( n * 9, 8 );
crc = ( crc >>> 8 ) ^ x;
}
crc = crc ^ (-1)
//convert to unsigned 32-bit int if needed
if (crc < 0) {crc += 4294967296}
return crc;
}
}
Also if you happen to be using Adobe Air, you can just use a ByteArray and avoid the stringToBytes function.

Categories