473,609 Members | 2,761 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Way to know bytes of an int in Python [with bits class thrown in]

7 New Member
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
May 18 '07 #1
15 5607
bartonc
6,596 Recognized Expert Expert
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
Expand|Select|Wrap|Line Numbers
  1. >>> aHex = hex(3000) # call built-in function to convert to hex
  2. >>> print aHex
  3. 0xbb8
  4. >>> bytes = aHex[2:].zfill(4) # slice off the '0x'
  5. >>> print bytes
  6. 0bb8
  7. >>> highByte = '0x%s' % bytes[0:2] #reformat with '0x' added to just the high byte
  8. >>> print highByte
  9. 0x0b
  10. >>> 
Let's see if you can get the low byte. We're here to help.
May 18 '07 #2
dshimer
136 Recognized Expert New Member
Just a curiosity but is there any built-in that would convert to binary? For example:
3000='101110111 000'
May 18 '07 #3
dansolo
7 New Member
First of all thanks,

the lowbyte comes from

lowByte = '0x%s' % bytes[2:4]

I've found also another solution:
Expand|Select|Wrap|Line Numbers
  1. # mod edit # added for completeness #
  2. import struct
  3. ################################
  4. def getByteLength(self, length):
  5.         temp = struct.pack('!h', length)
  6.         byteList = [firstLength, secondLength] = struct.unpack('BB', temp)
  7.         return list(byteList)
  8.  
to obtain a list in which the elements are the needed bytes
May 18 '07 #4
bartonc
6,596 Recognized Expert Expert
Just a curiosity but is there any built-in that would convert to binary? For example:
3000='101110111 000'
While it's true that
>>> int('101', 2)
5
>>>
There is no bit or byte type to call for conversion to base 2.
May 18 '07 #5
bartonc
6,596 Recognized Expert Expert
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:
Expand|Select|Wrap|Line Numbers
  1. def Byte2Bits(value):
  2.     # Create a list of bits to convert big endian wise
  3.     data = []
  4.     outStr = ""
  5.     for i in range(8):
  6.         value, rem = divmod(value, 2)
  7.         data.insert(0, rem)
  8.  
  9.     for pos, i in enumerate(data):
  10.         if not (pos % 4):
  11.             outStr += " "
  12.         outStr += str(i)
  13.     return outStr
  14.  
  15.  
  16. def Base2Repr(value):
  17.     # Create a list of bytes to convert big endian wise
  18.     data = []
  19.     outStr = ""
  20.     while value:
  21.         value, rem = divmod(value, 256)
  22.         data.insert(0, rem)
  23.     for i in data:
  24.         outStr += Byte2Bits(i)
  25.     return outStr[1:]
  26.  
  27.  
  28. class bits(object):
  29.     def __init__(self, value):
  30.         self.value = value
  31.  
  32.     def __repr__(self):
  33.         return Base2Repr(self.value)
  34.  
  35.  
  36.  
  37. if __name__ == "__main__":
  38.     b = bits(0xf5a5)
  39.     print b
  40.  
1111 0101 1010 0101
May 18 '07 #6
bvdet
2,851 Recognized Expert Moderator Specialist
Just a curiosity but is there any built-in that would convert to binary? For example:
3000='101110111 000'
I don't think so, but I made this up:
Expand|Select|Wrap|Line Numbers
  1. def ConvDecToBaseVar(num, base):
  2.     if base > 10 or base < 2:
  3.         raise ValueError, 'The base number must be between 2 and 10.'
  4.     if num == 0: return 0
  5.     ans = ''
  6.     while num != 0:
  7.         num, rem = divmod(num, base)
  8.         ans =  str(rem)+ans
  9.     return int(ans)
  10.  
  11. '''
  12. >>> ConvDecToBaseVar(3000,2)
  13. 101110111000L
  14. >>>
  15. '''
May 18 '07 #7
dshimer
136 Recognized Expert New Member
I was just curious about a built-in but that is absolutely Beautiful!
May 18 '07 #8
bartonc
6,596 Recognized Expert Expert
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?
May 18 '07 #9
bvdet
2,851 Recognized Expert Moderator Specialist
I was intrigued by a problem Motoma tackled and posted to Python Articles.
http://www.thescripts.com/forum/thread648799.html
May 18 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

10
3270
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 'sizeof(char)'. It seems that I could use bitset<8> to represent a byte in my code --- if you have a better suggestion, I welcome it --- but that still leaves me with the question of how to write those bitsets to an image file as big-endian bytes...
19
2851
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 o1,o2,o3, range 0 .. 2^8-1 How to do this in a clever way? (The 6 bits integers represent characters in range A-Z and 0-9)
19
5851
by: Lorenzo J. Lucchini | last post by:
My code contains this declaration: : typedef union { : word Word; : struct { : byte Low; : byte High; : } Bytes; : } reg;
161
7795
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.. (After reading that
0
1228
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) say. I added some stuff to fixedint.py to make
9
2088
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 <string> #include <limits> class Simple {
10
3331
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 = bits = bit_value print "\tBit Array:"
3
3132
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 store some value into pData which occupies pData and pData. Now I want to shift these two bytes to the left for 9 bits and still store them in pData. The data now should span from the bit0 in pData to bit1 in pData.
33
1804
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) { unsigned short s = 65535; printf("Size of unsigned short: %d bytes\n", sizeof(unsigned short)); // 2 bytes - OK
0
8047
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
8552
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
8376
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6975
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6044
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5503
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
4006
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
4063
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1372
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.