473,804 Members | 3,424 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Fastest way to convert a byte of integer into a list

Hello,

I'm trying to find a way to convert an integer (8-bits long for
starters) and converting them to a list, e.g.:

num = 255
numList = [1,1,1,1,1,1,1,1]

with the first element of the list being the least significant, so
that i can keep appending to that list without having to worry about
the size of the integer. I need to do this because some of the
function call can return a 2 lots of 32-bit numbers. I have to find a
way to transport this in a list... or is there a better way?

Jul 12 '07
12 5075
On Jul 13, 3:46 pm, "mensana...@aol .com" <mensana...@aol .comwrote:
On Jul 13, 5:17 am, Paul McGuire <pt...@austin.r r.comwrote:


On Jul 12, 5:34 pm, Godzilla <godzillais...@ gmail.comwrote:
Hello,
I'm trying to find a way to convert an integer (8-bits long for
starters) and converting them to a list, e.g.:
num = 255
numList = [1,1,1,1,1,1,1,1]
with the first element of the list being the least significant, so
that i can keep appending to that list without having to worry about
the size of the integer. I need to do this because some of the
function call can return a 2 lots of 32-bit numbers. I have to find a
way to transport this in a list... or is there a better way?
Standing on the shoulders of previous posters, I put this together.
-- Paul

But aren't we moving backwards? The OP did ask for the fastest way.

I put this together (from other posters and my own):

import gmpy
import time

y = 2**177149 - 1

# init list of tuples by byte
bytebits = lambda num : [num >i & 1 for i in range(8)]
bytes = [ tuple(bytebits( i)) for i in range(256) ]
# use bytes lookup to get bits in a 32-bit integer
bits = lambda num : sum((bytes[num >i & 255] for i in range(0,32,8)),
())
# use base-2 log to find how many bits in an integer of arbitrary
length
from math import log,ceil
log_of_2 = log(2)
numBits = lambda num : int(ceil(log(nu m)/log_of_2))
# expand bits to integers of arbitrary length
arbBits = lambda num : sum((bytes[num >i & 255] for i in
range(0,numBits (num),8)),())
t0 = time.time()
L = arbBits(y)
t1 = time.time()
print 'Paul McGuire algorithm:',t1-t0

t0 = time.time()
L = [y >i & 1 for i in range(177149)]
t1 = time.time()
print ' Matimus algorithm:',t1-t0

x = gmpy.mpz(2**177 149 - 1)
t0 = time.time()
L = [gmpy.getbit(x,i ) for i in range(177149)]
t1 = time.time()
print ' Mensanator algorithm:',t1-t0

## Paul McGuire algorithm: 17.4839999676
## Matimus algorithm: 3.28100013733
## Mensanator algorithm: 0.125- Hide quoted text -

- Show quoted text -
Oof! Pre-calculating those byte bitmasks doesn't help at all! It
would seem it is faster to use a single list comp than to try to sum
together the precalcuated sublists.

I *would* say though that it is somewhat cheating to call the other
two algorithms with the hardcoded range length of 177149, when you
know this is the right range because this is tailored to fit the input
value 2**177149-1. This would be a horrible value to use if the input
number were something small, like 5. I think numBits still helps here
to handle integers of arbitrary length (and only adds a slight
performance penalty since it is called only once).

-- Paul

Jul 14 '07 #11
On Jul 14, 5:49?pm, Paul McGuire <pt...@austin.r r.comwrote:
On Jul 13, 3:46 pm, "mensana...@aol .com" <mensana...@aol .comwrote:


On Jul 13, 5:17 am, Paul McGuire <pt...@austin.r r.comwrote:
On Jul 12, 5:34 pm, Godzilla <godzillais...@ gmail.comwrote:
Hello,
I'm trying to find a way to convert an integer (8-bits long for
starters) and converting them to a list, e.g.:
num = 255
numList = [1,1,1,1,1,1,1,1]
with the first element of the list being the least significant, so
that i can keep appending to that list without having to worry about
the size of the integer. I need to do this because some of the
function call can return a 2 lots of 32-bit numbers. I have to find a
way to transport this in a list... or is there a better way?
Standing on the shoulders of previous posters, I put this together.
-- Paul
But aren't we moving backwards? The OP did ask for the fastest way.
I put this together (from other posters and my own):
import gmpy
import time
y = 2**177149 - 1
# init list of tuples by byte
bytebits = lambda num : [num >i & 1 for i in range(8)]
bytes = [ tuple(bytebits( i)) for i in range(256) ]
# use bytes lookup to get bits in a 32-bit integer
bits = lambda num : sum((bytes[num >i & 255] for i in range(0,32,8)),
())
# use base-2 log to find how many bits in an integer of arbitrary
length
from math import log,ceil
log_of_2 = log(2)
numBits = lambda num : int(ceil(log(nu m)/log_of_2))
# expand bits to integers of arbitrary length
arbBits = lambda num : sum((bytes[num >i & 255] for i in
range(0,numBits (num),8)),())
t0 = time.time()
L = arbBits(y)
t1 = time.time()
print 'Paul McGuire algorithm:',t1-t0
t0 = time.time()
L = [y >i & 1 for i in range(177149)]
t1 = time.time()
print ' Matimus algorithm:',t1-t0
x = gmpy.mpz(2**177 149 - 1)
t0 = time.time()
L = [gmpy.getbit(x,i ) for i in range(177149)]
t1 = time.time()
print ' Mensanator algorithm:',t1-t0
## Paul McGuire algorithm: 17.4839999676
## Matimus algorithm: 3.28100013733
## Mensanator algorithm: 0.125

Oof! Pre-calculating those byte bitmasks doesn't help at all! It
would seem it is faster to use a single list comp than to try to sum
together the precalcuated sublists.

I *would* say though that it is somewhat cheating to call the other
two algorithms with the hardcoded range length of 177149, when you
know this is the right range because this is tailored to fit the input
value 2**177149-1. This would be a horrible value to use if the input
number were something small, like 5. I think numBits still helps here
to handle integers of arbitrary length (and only adds a slight
performance penalty since it is called only once).
I agree. But I didn't want to compare your numBits
against gmpy's numdigits() which I would normally use.
But since the one algorithm required a hardcoded number,
I thought it best to hardcode all three.

I originally coded this stupidly by converting
the number to a string and then converting to
a list of integers. But Matimus had already posted
his which looked a lot better than mine, so I didn't.

But then I got to wondering if Matimus' solution
requires (B**2+B)/2 shift operations for B bits.

My attempt to re-code his solution to only use B
shifts didn't work out and by then you had posted
yours. So I did the 3-way comparison using gmpy's
direct bit comparison. I was actually surprised at
the difference.

I find gmpy's suite of bit manipulation routines
extremely valuable and use them all the time.
That's another reason for my post, to promote gmpy.

It is also extremely important to keep coercion
out of loops. In other words, never use literals,
only pre-coerced constants. For example:

import gmpy
def collatz(n):
ONE = gmpy.mpz(1)
TWO = gmpy.mpz(2)
TWE = gmpy.mpz(3)
while n != ONE:
if n % TWO == ONE:
n = TWE*n + ONE
else:
n = n/TWO
collatz(gmpy.mp z(2**177149-1))
>
-- Paul
Jul 15 '07 #12
On 7 13 , 6 34 , Godzilla <godzillais...@ gmail.comwrote:
Hello,

I'm trying to find a way to convert an integer (8-bits long for
starters) and converting them to a list, e.g.:

num = 255
numList = [1,1,1,1,1,1,1,1]

with the first element of the list being the least significant, so
that i can keep appending to that list without having to worry about
the size of the integer. I need to do this because some of the
function call can return a 2 lots of 32-bit numbers. I have to find a
way to transport this in a list... or is there a better way?
my clone *bin* function from python3000
def _bin(n, count=32):
"""returns the binary of integer n, using count number of digits"""
return ''.join([str((n >i) & 1) for i in range(count-1, -1, -1)])

Jul 15 '07 #13

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

Similar topics

17
2334
by: DraguVaso | last post by:
Hi, I need to find the FASTEST way to get a string in a Loop, that goes from "a" to "ZZZZZZZZZZZZZZZZZ". So it has to go like this: a b .... z
6
5495
by: Jonathan | last post by:
I am hoping that someone more experienced than myself can point me towards what might be the fastest data lookup method to use for storing ip addresses. My situation is that I will need to maintain a list of perhaps 50 ip addresses to be used in a packet sniffing application. For each packet that goes through the application (which will be monitoring all traffic through a switch), I need to see if an entry for the source ip of that packet...
5
716
by: Daniel | last post by:
in C# fastest way to convert a string into a MemoryStream
9
12690
by: Charles Law | last post by:
Suppose I have a structure Private Structure MyStruct Dim el1 As Byte Dim el2 As Int16 Dim el3 As Byte End Structure I want to convert this into a byte array where
14
29734
by: Charles Law | last post by:
I thought this had come up before, but I now cannot find it. I have a byte array, such as Dim a() As Byte = {1, 2, 3, 4} I want to convert this to an Int32 = 01020304 (hex). If I use BitConverter, I get 04030201.
6
53730
by: moondaddy | last post by:
I'm writing an app in vb.net 1.1 and need to convert a byte array into a string, and then from a string back to a byte array. for example Private mByte() as New Byte(4){11,22,33,44} Now how do I convert it to: dim myStr as string = "11,22,33,44"
5
8656
by: Bob Homes | last post by:
In VB6, foreground and background colors of controls had to be assigned a single number. If you knew the RGB values for the color, you still had to convert them into the single number accepatable to the VB6 controls. In VB.NET, you can't set colors that way anymore, now you have to use a "color". There is a way to convert RGB values to a "color", using the Color.FromARGB method. But there doens't seem to be a way to convert the old...
24
2296
by: ThunderMusic | last post by:
Hi, The subject says it all... I want to use a byte and use it as byte* so I can increment the pointer to iterate through it. What is the fastest way of doing so in C#? Thanks ThunderMusic
0
1445
by: laviewpbt | last post by:
Fist ,Add a new class named "CImage",then copythe following codes and paste to it. Option Explicit Private Type BITMAPFILEHEADER bfType As Integer bfSize As Long bfReserved1 As Integer
0
9710
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9589
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10593
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
6858
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4304
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
2
3830
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.