0

I've two integer of one byte, so each integer can be in the range 0-255. Suppose

    a = 247
    b = 8

Now the binary representation of each is:

   a = 11110111
   b = 00001000

What I need are the following operations:

1) Concat those two binary sequence, so following the example, "a" concat "b" would result in:

 concat = 1111011100001000 -> that is 63240

2) Consider only the first n most significative bits, suppose the first 10 bits, this would resoult in:

 msb = 1111011100000000

3) Revert the bits order, this would result in:

 reverse = 0001000011101111

For the question number 2 I know it's just a shift operation, for the 3 I've guessed to convert in hex, then swap and then convert to integer, but I guess also that there are more elegant way.

For the number 1, I've wrote this solution, but I'm looking for something more elegant and performant:

 a = 247
 b = 8

 first = hex(a)[2:].zfill(2)
 second = hex(b)[2:].zfill(2)

 concat = int("0x"+first+second,0)

Thank you

1
  • ...any comment on the answer? It replaces your expensive function calls with a bit of simple arithmetic, it should be the "more elegant and performant" solution you're looking for. Commented Jun 13, 2019 at 16:23

1 Answer 1

1

Those operations are basic bit manipulations, with the exception of the last step:

  1. 247, left shift by 8 bits (= move to higher byte)
  2. keep 8 as it is (= lower byte)
  3. add those results
  4. bit-and with a mask that zeroes out the last 6 bits
  5. reverse the bit order (not a bit operation; more methods here)

In Python 2.7 code:

a = 247 << 8
print "a = {0: >5} - {1:0>16}".format(a, bin(a)[2:])

b = 8
print "b = {0: >5} - {1:0>16}".format(b, bin(b)[2:])

c = a + b
print "c = {0: >5} - {1:0>16}".format(c, bin(c)[2:])

d = c & ~63  # 63 = 111111, ~63 is the inverse
print "d = {0: >5} - {1:0>16}".format(d, bin(d)[2:])

e = int('{:08b}'.format(d)[::-1], 2)
print "e = {0: >5} - {1:0>16}".format(e, bin(e)[2:])

Output

a = 63232 - 1111011100000000
b =     8 - 0000000000001000
c = 63240 - 1111011100001000
d = 63232 - 1111011100000000
e =   239 - 0000000011101111
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.