Jube
Jube

Reputation: 184

Converting an int into a 32-bit binary line with extra stuff

A user inputs a string of 8 characters that's then converted to string and put into an array to be played with.

With those 8 digits I'd like to be able to convert them into 32-bit binary e.g

int = 12,345,678

int = -10,000,000

Ive tried using "StudentID = Integer.toBinaryString(sID);" However it does not produce the addition 0's to make up the 32-bits (probaby more efficient). Like this

How am I able to allow all integers to be displayed in a 32-bit string, as well as accept negative numbers (that i can use two complement's negating thing)?

Awesome reference; http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html

Upvotes: 3

Views: 11191

Answers (1)

RealSkeptic
RealSkeptic

Reputation: 34628

For integers, you can use this trick:

String result = Long.toBinaryString( sID & 0xffffffffL | 0x100000000L ).substring(1);

This puts the integer in a long, adds a single bit to its left, which means that the toBinaryString will have 33 digits, and then takes the right-hand 32 digits (dropping the extra 1 that was added).

A Java 8 version:

String result = Long.toBinaryString( Integer.toUnsignedLong(sID) | 0x100000000L ).substring(1);

Upvotes: 9

Related Questions