# Convert Negative Integers into Signed Binary?

I'm relatively new to Mathematica and have been struggling with this problem for several days.

I have a string of integer data, ranging from -2044 to 2044. So this looks something like {-2044,-2040,-2032......2037,2040,2044} (there is no pattern in the data).

However, now I need to export this string of data to a text file in Signed binary representation.

There is a convenient way to convert positive base ten integers into binary with BaseForm, but I cannot find a way to convert negative base ten integers into Signed binary.

If anyone has any tips on how to do that, I'd appreciate the help! Thanks.

• Maybe I misunderstood you, but what's wrong with the output of BaseForm[-2044, 2]? – Lukas Lang Sep 15 '17 at 14:16
• @Mathe172 I think he doesn't want to write the numbers in binary as a mathematician would. He wants to create a certain representation that computers use, where the first bit denotes the sign. – Szabolcs Sep 15 '17 at 14:23

You can implement it easily:

Clear[signedBinary]
signedBinary[bits_][x_] :=
IntegerDigits[Mod[x + 2^bits, 2^bits], 2, bits]

signedBinary[8] /@ {-1, 0, 10, 127}
(* {{1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 0, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 1}} *)


Of course, the number of bits is important and needs to be specified. In your implementation, you may want to include a check for out-of-range numbers.

To also convert to a string,

StringJoin@*Map[ToString]@*signedBinary[8] /@ {-1, 0, 10, 127}


@* means Composition.

• Thanks so much for the feedback! Yes that is an excellent solution. Very much appreciated. – Karl Haebler Sep 15 '17 at 14:48
• Hey sorry I actually am not getting my "String Join" to work. I actually do need the output for a single input to be a string, such that if the input is a vector then the output is a vector. But unfortunately I get the following error when I copy and paste your code into my notebook "StringJoin::string: String expected at position 1 in StringJoin[{0,0,0,0,0,0,0,0,1,0,0,0}[-1]]." And a similar error repeated several times. o you have any suggestions? Thanks – Karl Haebler Sep 15 '17 at 15:49
• Maybe I'm using the wrong terminology, by string I mean like 101000110010 etc, just a list of 12 bits. And then the output, when given a vector input, should be a vector like {101000110010,100111111000,100000001100} etc – Karl Haebler Sep 15 '17 at 15:52
• Ahhhhhhhh I'm so sorry I was using your function wrong. It totally works. Thanks so much! – Karl Haebler Sep 15 '17 at 15:55