7

I am new to Python. In Perl, to set specific bits to a scalar variable(integer), I can use vec() as below.

#!/usr/bin/perl -w  
$vec = '';
vec($vec,  3, 4) = 1;  # bits 0 to 3
vec($vec,  7, 4) = 10; # bits 4 to 7
vec($vec, 11, 4) = 3;  # bits 8 to 11
vec($vec, 15, 4) = 15; # bits 12 to 15

print("vec() Has a created a string of nybbles,
in hex: ", unpack("h*", $vec), "\n");

Output:

vec() Has a created a string of nybbles, 
      in hex: 0001000a0003000f

I was wondering how to achieve the same in Python, without having to write bit manipulation code and using struct.pack manually?

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
rajachan1982
  • 71
  • 1
  • 3
  • When you say bit manipulation code you mean bitshift << >>? – user2958652 Dec 10 '13 at 02:17
  • 2
    You say it sets bits 0 to 3, 4 to 7, etc but it sets nibbles 3 (bits 12 to 15), 7 (bits 28 to 31), etc. Either way, it should be easy to write your own `vec` if there isn't an equivalent. – ikegami Dec 10 '13 at 03:29
  • 2
    Maybe the question [Bit array in Python](http://stackoverflow.com/q/11669178/2157640) would help. – Palec Dec 10 '13 at 03:45

2 Answers2

0

Not sure how the vec function works in pearl (haven't worked with the vec function). However, according to the output you have mentioned, the following code in python works fine. I do not see the significance of the second argument. To call the vec function this way: vec(value, size). Every time you do so, the output string will be concatenated to the global final_str variable.


final_vec = ''
def vec(value, size):
    global final_vec
    prefix = ''
    str_hex = str(hex(value)).replace('0x','')
    str_hex_size = len(str_hex)
    for i in range (0, size - str_hex_size):
        prefix = prefix + '0'
    str_hex = prefix + str_hex
    final_vec = final_vec + str_hex
    return 0    
vec(1, 4)
vec(10, 4)
vec(3, 4)
vec(15, 4)
print(final_vec)
Overclock
  • 44
  • 1
0

If you really want to create a hex string from nibbles, you could solve it this way

nibbles = [1,10,3,15]
hex = '0x' + "".join([ "%04x" % x for x in nibbles])