Hi,
I need to know the byte which a number is made of. For example, let's suppose I have
i = 3000
I would like to know if there is a way to get the single byte of the number (0x0B and 0xB8).
Thanks in advance,
Daniele
15 5588
Hi,
I need to know the byte which a number is made of. For example, let's suppose I have
i = 3000
I would like to know if there is a way to get the single byte of the number (0x0B and 0xB8).
Thanks in advance,
Daniele
-
>>> aHex = hex(3000) # call built-in function to convert to hex
-
>>> print aHex
-
0xbb8
-
>>> bytes = aHex[2:].zfill(4) # slice off the '0x'
-
>>> print bytes
-
0bb8
-
>>> highByte = '0x%s' % bytes[0:2] #reformat with '0x' added to just the high byte
-
>>> print highByte
-
0x0b
-
>>>
Let's see if you can get the low byte. We're here to help.
Just a curiosity but is there any built-in that would convert to binary? For example:
3000='101110111000'
First of all thanks,
the lowbyte comes from
lowByte = '0x%s' % bytes[2:4]
I've found also another solution: -
# mod edit # added for completeness #
-
import struct
-
################################
-
def getByteLength(self, length):
-
temp = struct.pack('!h', length)
-
byteList = [firstLength, secondLength] = struct.unpack('BB', temp)
-
return list(byteList)
-
to obtain a list in which the elements are the needed bytes
Just a curiosity but is there any built-in that would convert to binary? For example:
3000='101110111000'
While it's true that
>>> int('101', 2)
5
>>>
There is no bit or byte type to call for conversion to base 2.
While it's true that
>>> int('101', 2)
5
>>>
There is no bit or byte type to call for conversion to base 2.
How 'bout this little goodie: - def Byte2Bits(value):
-
# Create a list of bits to convert big endian wise
-
data = []
-
outStr = ""
-
for i in range(8):
-
value, rem = divmod(value, 2)
-
data.insert(0, rem)
-
-
for pos, i in enumerate(data):
-
if not (pos % 4):
-
outStr += " "
-
outStr += str(i)
-
return outStr
-
-
-
def Base2Repr(value):
-
# Create a list of bytes to convert big endian wise
-
data = []
-
outStr = ""
-
while value:
-
value, rem = divmod(value, 256)
-
data.insert(0, rem)
-
for i in data:
-
outStr += Byte2Bits(i)
-
return outStr[1:]
-
-
-
class bits(object):
-
def __init__(self, value):
-
self.value = value
-
-
def __repr__(self):
-
return Base2Repr(self.value)
-
-
-
-
if __name__ == "__main__":
-
b = bits(0xf5a5)
-
print b
-
1111 0101 1010 0101
bvdet 2,851
Expert Mod 2GB
Just a curiosity but is there any built-in that would convert to binary? For example:
3000='101110111000'
I don't think so, but I made this up: - def ConvDecToBaseVar(num, base):
-
if base > 10 or base < 2:
-
raise ValueError, 'The base number must be between 2 and 10.'
-
if num == 0: return 0
-
ans = ''
-
while num != 0:
-
num, rem = divmod(num, base)
-
ans = str(rem)+ans
-
return int(ans)
-
-
'''
-
>>> ConvDecToBaseVar(3000,2)
-
101110111000L
-
>>>
-
'''
I was just curious about a built-in but that is absolutely Beautiful!
I was just curious about a built-in but that is absolutely Beautiful!
It's beautiful, all right (ain't BV good). But what about nibble formatting?
Just a curiosity but is there any built-in that would convert to binary? For example:
3000='101110111000'
-
def dectobin(number):
-
if number < 1: return ""
-
else:return dectobin(number/2) + str(number & 1)
-
-
def dectobin(number):
-
if number < 1: return ""
-
else:return dectobin(number/2) + str(number & 1)
-
VERY nice, GD. So, let's see: If <edit: this isn't right [the integer division of number by 2]> number is odd, then the next [L]MSb is a one... Am I getting that right? And where/how did you dream up that algorithm?
VERY nice, GD. So, let's see: If <edit: this isn't right [the integer division of number by 2]> number is odd, then the next [L]MSb is a one... Am I getting that right? And where/how did you dream up that algorithm?
the & operator is just to test the LSB of binary division.
say for example 14 divide by 2. in binary division of these 2 numbers,
1110 divide by 10 , as you slowly progress, you will reach the LSB and it will always be 0 or 1.
In & operations, a true and true is a true. So if the LSB is 0, & with 1 will be 0. (tested no remainder) . if LSB is 1, & with 1 is a 1, so there's remainder.
( in this case, 14/2 is remainder 0, so the bit tested is 0 )
and then we do 7/2 , 3/2 and so on.....the rest of the code is just to chain together all these 0's and 1's tested.
hope i didn't miss anything...
I don't think so, but I made this up: - def ConvDecToBaseVar(num, base):
-
if base > 10 or base < 2:
-
raise ValueError, 'The base number must be between 2 and 10.'
-
if num == 0: return 0
-
ans = ''
-
while num != 0:
-
num, rem = divmod(num, base)
-
ans = str(rem)+ans
-
return int(ans)
-
-
'''
-
>>> ConvDecToBaseVar(3000,2)
-
101110111000L
-
>>>
-
'''
Gotta love reusable code, eh?
bvdet 2,851
Expert Mod 2GB
Gotta love reusable code, eh?
Yes. Here's some more recycling - - def ConvDecToBaseVar3(num, base):
-
if base > 16 or base < 2:
-
raise ValueError, 'The base number must be between 2 and 16.'
-
dd = dict(zip(range(16), [hex(i).split('x')[1] for i in range(16)]))
-
if num == 0: return ''
-
num, rem = divmod(num, base)
-
return ConvDecToBaseVar3(num, base)+dd[rem]
- >>> ConvDecToBaseVar3(123456789, 16)
-
'75bcd15'
-
>>> ConvDecToBaseVar3(2**200, 16)
-
'100000000000000000000000000000000000000000000000000'
-
>>> ConvDecToBaseVar3(2**200, 7)
-
'141246066533632643213232344050606053061443446006544361632102630555343054'
-
>>>
It's not suitable for very long numbers due to the recursion limit.
bvdet 2,851
Expert Mod 2GB
This is considerably more efficient than the previous version: - def ConvDecToBaseVar3(num, base, dd=False):
-
if base > 16 or base < 2:
-
raise ValueError, 'The base number must be between 2 and 16.'
-
if not dd:
-
dd = dict(zip(range(16), [hex(i).split('x')[1] for i in range(16)]))
-
if num == 0: return ''
-
num, rem = divmod(num, base)
-
return ConvDecToBaseVar3(num, base, dd)+dd[rem]
This avoids the recursion limit: - def ConvDecToBaseVar4(num, base):
-
if num < 2: return str(num)
-
if base > 16 or base < 2:
-
raise ValueError, 'The base number must be between 2 and 16.'
-
dd = dict(zip(range(16), [hex(i).split('x')[1] for i in range(16)]))
-
ans = ''
-
while num != 0:
-
num, rem = divmod(num, base)
-
ans = str(rem)+ans
-
return ans
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Kristian Nybo |
last post by:
Hi,
I'm writing a simple image file exporter as part of a school project. To
implement my image format of choice I need to work with big-endian
bytes, where 'byte' of course means '8 bits', not...
|
by: becte |
last post by:
I need to use three bytes to store four 6-bit integers (4 * 6 = 3 * 8)
like this
11111122|22223333|33444444
Suppose the input is, int c1, c2, c3, c4, range 0 .. 2^6 -1
and the output is int...
|
by: Lorenzo J. Lucchini |
last post by:
My code contains this declaration:
: typedef union {
: word Word;
: struct {
: byte Low;
: byte High;
: } Bytes;
: } reg;
|
by: KraftDiner |
last post by:
I was under the assumption that everything in python was a refrence...
so if I code this:
lst =
for i in lst:
if i==2:
i = 4
print lst
I though the contents of lst would be modified.....
|
by: Andy Sy |
last post by:
Hi Dan,
I find that when doing bit-twiddling in pure Python,
fixed-width integer support is an extremely handy
capability to have in Python regardless of what
the apologists (for its absence)...
|
by: Alex Buell |
last post by:
I just wrote the following and have a question: Why does my code gets
it wrong with the class Simple? See last show_size<Simple> function call
in main () as below:
#include <iostream>
#include...
|
by: Michael Yanowitz |
last post by:
Is it possible to have a static variable in Python -
a local variable in a function that retains its value.
For example, suppose I have:
def set_bit (bit_index, bit_value):
static bits = ...
|
by: Cindy |
last post by:
I am struggling over a simple way to shift multi bytes for certain
bits. Hope someone can help. For example, I open a memory space for 10
bytes:
unsigned char *pData = new unsigned char;
then...
|
by: Hahnemann |
last post by:
Does anybody know the answer to the following? An unsigned short is 2
bytes long. Why is the following file created as 4 bytes instead of
2?
file = fopen("data.bin", "wb");
if (file != NULL)...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
| |