473,554 Members | 4,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert an integer value to a 4-byte array

Fellow JavaScripters,

I am looking for code or implementation ideas for converting an integer
variable to a four-byte array. I'm porting some of my code from C#,
where I make use of their BitConverter utility class, but am still
feeling my way around a bit here with JavaScript.

The idea is that each of the four bytes that comprise an integer (I
presume numeric types in JavaScript are/can be made four bytes?) are
extracted, and then each of the four bytes are stored in the array...

Any help or pointers would be appreciated.
Thank you,

--Mike

Aug 11 '05 #1
9 36769
JavaScript C# four-byte array

---------------------
JavaScript
That was the idea.

Are you trying to find the crossover point of what ancestor
that successfully developed into a what.

A monkey.

What would Jesus use ?

Oil ,Gas and SUV ?

--------------------------------

Make sure not to miss the class what ever your are in.

<mp*******@gmai l.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Fellow JavaScripters,

I am looking for code or implementation ideas for converting an integer
variable to a four-byte array. I'm porting some of my code from C#,
where I make use of their BitConverter utility class, but am still
feeling my way around a bit here with JavaScript.

The idea is that each of the four bytes that comprise an integer (I
presume numeric types in JavaScript are/can be made four bytes?) are
extracted, and then each of the four bytes are stored in the array...

Any help or pointers would be appreciated.
Thank you,

--Mike


Aug 11 '05 #2
"Make sure not to miss the class what ever your are in."

I can't tell if yours is a spam posting or not, but this last line is
interesting. I know plenty of students who post looking for homework
help. I'm not one of them--this is for a pet project of mine.

--Mike
Master of Science / Computer Science, University of Florida, 2002

Aug 11 '05 #3
mp*******@gmail .com wrote:
[...]
The idea is that each of the four bytes that comprise an integer (I
presume numeric types in JavaScript are/can be made four bytes?) are
extracted, and then each of the four bytes are stored in the array...


Unfortunately, they're not... Javascript is defined to store its numbers as
8-byte IEEE floating-point types.

The only way you're going to be able to do this is to do modulos and
divisions in order to convert to base 256. Not particularly hard, but slow
and annoying.

A few weeks ago someone posted wanting to convert a Javascript number into a
*floating point* byte array. Now, that was hard...

--
+- David Given --McQ-+ "P.S. If you do not receive this, of course it
| dg@cowlark.com | must have been miscarried; therefore I beg you to
| (dg@tao-group.com) | write and let me know." --- Sir Boyle Roche, in a
+- www.cowlark.com --+ letter

Aug 11 '05 #4
well i've done a quicky in javascript and you might want to stick it in a
loop rather than the way i've done it but

bytes=new Array(3);
x=100000;
bytes[3]=x & (255);
x=x>>8
bytes[2]=x & (255);
x=x>>8
bytes[1]=x & (255);
x=x>>8
bytes[0]=x & (255);

document.write (bytes[0], " ");
document.write (bytes[1], " ");
document.write (bytes[2], " ");
document.write (bytes[3]);
HTH

Darren
<mp*******@gmai l.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Fellow JavaScripters,

I am looking for code or implementation ideas for converting an integer
variable to a four-byte array. I'm porting some of my code from C#,
where I make use of their BitConverter utility class, but am still
feeling my way around a bit here with JavaScript.

The idea is that each of the four bytes that comprise an integer (I
presume numeric types in JavaScript are/can be made four bytes?) are
extracted, and then each of the four bytes are stored in the array...

Any help or pointers would be appreciated.
Thank you,

--Mike

Aug 11 '05 #5
JRS: In article <oS************ *****@newsfe5-win.ntli.net>, dated Thu,
11 Aug 2005 11:44:20, seen in news:comp.lang. javascript, David Given
<dg@cowlark.com > posted :
mp*******@gmai l.com wrote:
[...]
The idea is that each of the four bytes that comprise an integer (I
presume numeric types in JavaScript are/can be made four bytes?) are
extracted, and then each of the four bytes are stored in the array...
Unfortunatel y, they're not... Javascript is defined to store its numbers as
8-byte IEEE floating-point types.


However, that format will hold the value of any 32-bit integer, whether
or not signed, exactly.
The only way you're going to be able to do this is to do modulos and
divisions in order to convert to base 256. Not particularly hard, but slow
and annoying.
Not the only way : shifts and masks will do it, and could be quicker,
FWIW.

I see one minor trap, probably affecting the different methods
differently : the sign bit. It may be best to extract it with
var NEG = (X<0) ; X = Math.abs(X)
and then OR or ADD it in to the top byte .... OTOH, maybe one can just
add 0x100000000 (2^32) and then convert, or add 2^31 and XOR the tip
with 0x80, or something like that. It rather depends on what you want.

Consider, for a start,
X = Math.pow(2,32)-Math.pow(2, 16) - 2*Math.pow(2, 8) - 4
A = []
J=4 ; while (J--) { A[J] = X & 0xFF ; X = X>>8 }
A // 255,254,253,252

You can get 6 bytes, and part of a seventh.
A few weeks ago someone posted wanting to convert a Javascript number into a
*floating point* byte array. Now, that was hard...


Not really : <URL:http://www.merlyn.demo n.co.uk/js-misc0.htm#IEEE> .

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Aug 11 '05 #6
Darren,

Thanks very much for your response. Your code does exactly what I was
looking for--excellent. I haven't tested it with all input, but at a
first cut, it's creating the arrays correctly.
From an optimization standpoint, any ideas on how to speed this up? It

will be called in a loop, 1000 times or so.

One idea I had is to not create the array in memory each time, but
actually pass it in as a parameter and reuse it. That should save 1000
dynamic array allocations (I'll do some metrics later).

If I know the integer is going to be bounded between 1 and 1000, one or
more of the chunks doesn't need to be calculated... I think only two
would need to be (255 * 255). So that should speed things up by two.

Also, what is the best format to perform bit operations with (the "&"
operator)? 255, or is a hex representation (0xFF or similar) better? In
this line, var a = x & (255), is the 255 being caster to a different
data type?

Aug 12 '05 #7
mp*******@gmail .com wrote:
Darren,

Thanks very much for your response. Your code does exactly what I was
looking for--excellent. I haven't tested it with all input, but at a
first cut, it's creating the arrays correctly.
From an optimization standpoint, any ideas on how to speed this up? It will be called in a loop, 1000 times or so.


I've 'function-ised' Darren's code below, it runs 10,000 'getBytes()' in
about 200ms (Firefox) or 220ms (IE) on a 2.4GH P4.

One idea I had is to not create the array in memory each time, but
actually pass it in as a parameter and reuse it. That should save 1000
dynamic array allocations (I'll do some metrics later).
You've gotta create the array sometime, and it takes very little time.
If I know the integer is going to be bounded between 1 and 1000, one or
more of the chunks doesn't need to be calculated... I think only two
would need to be (255 * 255). So that should speed things up by two.
For very large sets of numbers that are all within a range it maybe
worth it but the time spent calculating how many loops to do may take
longer than doing the loops.

There is an optimised version below called getBytes0 that stops looping
when x =0, it trims about 10% from the time but the array will have
undefined values for the missed loops - dealing with that may take back
the 10%.

Also, what is the best format to perform bit operations with (the "&"
operator)? 255, or is a hex representation (0xFF or similar) better? In
this line, var a = x & (255), is the 255 being caster to a different
data type?


Testing 255 vs 0xFF made no measurable difference, if there may be other
more meaningful optimisations.

<div id="msg2" style="font-weight:bold;"></div>
<p>Click reload to run again...</p>

<p>Enter a number and click elsewhere in the document</p>
<input type="text" onblur="
document.getEle mentById('msg') .innerHTML =
getBytes(this.v alue).join('<br >');">
<p></p>
<div id="msg"></div>

<script type="text/javascript">

// Does exactly 4 loops
function getBytes( x ){
var bytes = [];
var i = 4;
do {
bytes[--i] = x & (255);
x = x>>8;
} while ( i )
return bytes;
}

// Stops looping when x = 0
function getBytes0( x ){
var bytes = [];
var i = 4;
do {
bytes[--i] = x&(255);
x = x>>8;
} while ( i && x > 0 )
return bytes;
}

/* Generate an array of numValues random integers
between 0 and 100,000, then do getBytes on them
and time it
*/

var j, sTime, fTime;
var numValues = 10000;
var randArray = [];
for ( j=0; j<numValues; j++) {
randArray[j] = (Math.random()* 100000) | 0;
}

j = numValues;
sTime = new Date();
while ( j-- ) {
getBytes( randArray[j] )
}
fTime = new Date();

document.getEle mentById('msg2' ).innerHTML =
( 'Doing ' + numValues + ' values took ' + (fTime - sTime) + 'ms');

</script>


--
Rob
Aug 12 '05 #8

<mp*******@gmai l.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Darren,

Thanks very much for your response. Your code does exactly what I was
looking for--excellent. I haven't tested it with all input, but at a
first cut, it's creating the arrays correctly.
From an optimization standpoint, any ideas on how to speed this up? It will be called in a loop, 1000 times or so.

one thing you could do is calculate the total value of each byte
respectivully instead of but shifting then mask off. ie

bytes=new Array(3);
x=16777217;
bytes[3]=x & (255);
bytes[2]=(x & (65280))/256;
bytes[1]=(x & (16711680))/65536;
bytes[0]=(x & (4278190080))/16777216;

processor wise i think this takes the same clock ticks as bitshifting but
i'm not sure of that.

One idea I had is to not create the array in memory each time, but
actually pass it in as a parameter and reuse it. That should save 1000
dynamic array allocations (I'll do some metrics later).

If I know the integer is going to be bounded between 1 and 1000, one or
more of the chunks doesn't need to be calculated... I think only two
would need to be (255 * 255). So that should speed things up by two. if the parameter is never more than i thousdand then you only need two bytes
rather than four.
Also, what is the best format to perform bit operations with (the "&"
operator)? 255, or is a hex representation (0xFF or similar) better? In
this line, var a = x & (255), is the 255 being caster to a different
data type?

What i did above was to colculate the values of isolating each byte/ masking
it off but i origionally did it in hex but converted it to decimal because i
assumed that would remove any need to convert it processor wise i could be
thinking backward about this.

Let me know how it goes.

Darren
Aug 12 '05 #9
JRS: In article <iX************ *****@news.optu s.net.au>, dated Fri, 12
Aug 2005 04:53:34, seen in news:comp.lang. javascript, RobG
<rg***@iinet.ne t.auau> posted :

Testing 255 vs 0xFF made no measurable difference, if there may be other
more meaningful optimisations.


One might also test whether using global var XX = 255 and using XX
elsewhere is significantly better or worse.

And whether superfluous parentheses and inessential semicolons matter!

ISTM possible that an implementation of javascript might be intelligent
enough to keep the 32-bit results of logical operations in that form for
as long as possible, and whether one can find a cunning way of using
that.

It occurs to me that an IEEE Double can only hold genuine numbers
(including +0 -0), +Inf, -Inf, and very many NaNs. It cannot, however,
rightly hold undefined or null.

Therefore a Number object must have data storage apart from the IEEE
float (or cheat by re-using NaN-space, as javascript only knows one
NaN).

Therefore, it could store, in the 8-byte float-space, a 4-byte integer,
and store in its extra storage which of the two was in use.
My code for the conversion, and the reverse, is now at
<URL:http://www.merlyn.demo n.co.uk/js-misc0.htm#I32>. However, it's
designed for display rather than speed.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demo n.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
Aug 12 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
6282
by: Grant Edwards | last post by:
I give up, how do I make this not fail under 2.4? fcntl.ioctl(self.dev.fileno(),0xc0047a80,struct.pack("HBB",0x1c,0x00,0x00)) I get an OverflowError: long int too large to convert to int ioctl() is expecting a 32-bit integer value, and 0xc0047a80 has the high-order bit set. I'm assuming Python thinks it's a signed value. How do I tell...
3
10262
by: Convert TextBox.Text to Int32 Problem | last post by:
Need a little help here. I saw some related posts, so here goes... I have some textboxes which are designed for the user to enter a integer value. In "old school C" we just used the atoi function and there you have it. So I enquired and found the Convert class with it's promising ToInt32 method, great... but it doesn't work. The thing keeps...
5
37266
by: Mika M | last post by:
Hi! I've made little code to convert string into hex string... Public ReadOnly Property ToHexString(ByVal text As String) As String Get Dim arrBytes As Integer() = CharsToBytes(text) Dim sb As StringBuilder = New StringBuilder For i As Integer = 0 To arrBytes.Length - 1
14
1463
by: Drew | last post by:
Hi All: I know I am missing something easy but I can't find the problem! I have a program which reads an integer as input. The output of the program should be the sum of all the digits in the integer that was entered. So, if 353 was entered, the output should be 11.
7
19203
by: elliotng.ee | last post by:
I have a text file that contains a header 32-bit binary. For example, the text file could be: %%This is the input text %%test.txt Date: Tue Dec 26 14:03:35 2006 00000000000000001111111111111111 11111111111111111111111111111111 00000000000000000000000000000000 11111111111111110000000000000000
7
6237
by: shellon | last post by:
Hi all: I want to convert the float number to sortable integer, like the function float2rawInt() in java, but I don't know the internal expression of float, appreciate your help!
11
15360
by: Yaniv | last post by:
Hi How can I convert Uint32 variable to System.drawing.color ?? Thanks in advanced Yaniv
6
16889
by: sweeet_addiction16 | last post by:
hello Im writin a code in c... can sum1 pls help me out in writing a c code to convert decimalnumber to hexadecimal number.The hexadecimal number generated has to be an unsigned long.
3
6321
by: =?Utf-8?B?U2hlbGRvbg==?= | last post by:
Hello - I have various times formatted like 00:00:00, so for example, 01:32:05 would be one thirty-two with five milliseconds. I need to convert this into seconds (an integer). First of all, I have been unable to use the mid() function like I did in vb 6.
28
19380
by: Fore | last post by:
Hello I am looking for some effecient way to convert a 32 bit unsigned integer to a 16 bit signed integer. All I want is the lower 16 bits of the 32 bit unsigned integer , with bit 15 (0..15) to used as the sign bit for the 16 bit signed integer. Any ideas/help greatly appreciated. Thanks.
0
7615
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7539
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7819
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7581
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6170
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3589
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2030
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1149
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
858
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.