2

I wish to convert a tensor of binary numbers, for example, [0,1,0,1,1] to an integer in tensorflow. In my case, the tensor is quite large, with a length of approximately 80 elements. Is there a way to do this efficiently?

2
  • What kind of integer are you hoping to get? 160000 bits is a bit more than will fit in a 64-bit integer. Is there some sort of batching going on? Commented Feb 10, 2017 at 1:32
  • @AllenLavoie Sorry. It is 80 bits in total. Commented Feb 10, 2017 at 8:35

1 Answer 1

3

This will almost certainly lead to overflows with length-80 binary Tensors, but the basic strategy would be to do a vectorized multiplication with a Tensor which has powers of two:

import tensorflow as tf

binary_string = tf.constant([1, 0, 0, 1, 1])

result = tf.reduce_sum(
    tf.cast(tf.reverse(tensor=binary_string, axis=[0]), dtype=tf.int64)
    * 2 ** tf.range(tf.cast(tf.size(binary_string), dtype=tf.int64)))

with tf.Session():
    print(result.eval())

Prints:

19
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.