Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: Decimal to binary


From   Jeffrey Simons <jsimons@usd.edu>
To   statalist@hsphsun2.harvard.edu
Subject   st: Decimal to binary
Date   Wed, 10 Mar 2004 09:53:40 -0600

Thanks to both nick and nikos.

Nick's solution works well provided that  I have a number value that takes
on 6 digits otherwise it assigns the value for code6 as missing

That is

var1
29 

Results in 

var1    binary  code1   code2   code3 code4 code5 code6
29      11101   1       1       1       0       1

But 

var1
29
35

Results in 

var1    binary  code1   code2   code3 code4 code5   code6
29      011101   0      1       1       1       0       1
35      100011   1      0       0       0       1       1

So , I can just make sure I include a data point that will require a 6 digit
binary code and it will work well.

Nikos solution seems to shift the numbers and puts in trailing zeros rather
than leading zeros

That is

var1
29

Expands to

var1     var2  v6 v5 v4  v3   v2  v1
29      11101  1  1   1   0    1   0


Thank you both for your prompt and thoughtful solutions.

-egenmore- on SSC has a function -base()- that
gets you halfway with this.

. egen binary = base(var1)
. forval i = 1/6 {
.          gen str1 code`i' = substr(binary,`i',1)
. } 

Nick 
n.j.cox@durham.ac.uk

> -----Original Message-----
> From: owner-statalist@hsphsun2.harvard.edu
> [mailto:owner-statalist@hsphsun2.harvard.edu]On Behalf Of
> Jeffrey Simons
> Sent: 10 March 2004 13:48
> To: statalist@hsphsun2.harvard.edu
> Subject: st: Re: decimal to binary conversion
> 
> 
> I want to take a variable that is in decimal format and
> convert it to a six
> digit binary number. Then take that and form six new
> indicator variables.
> 
> For example,
> 
> . inbase 2 29
> 11101
> 
> Provides this. I would like to write a do file to loop
> through the values of
> a variable and do this. Converting the answer to six new indicator
> variables.
> 
> So if var1 took on values of 15, 29, 35, ...
> I'd like to get
> 
> var1    v1a v1b v1c v1d v1e v1f
> 15      0   0   1   1   1   1
> 29      0   1   1   1   0   1
> 35      1   0   0   0   1   1
> ....


*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index