Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: re: return a specific bit from integer variable


From   Kit Baum <baum@bc.edu>
To   statalist@hsphsun2.harvard.edu
Subject   st: re: return a specific bit from integer variable
Date   Sun, 4 Oct 2009 09:03:24 -0400

<>
Given an integer between 0-255 and the desired bit to be retrieved (counting from the left or high-order bit), this routine will give you the binary form of the integer and the bit as locals:

mata: mata clear
mata:
void bit(real scalar v, real scalar w)
{
	string vector d, b
	d=("0000","0001","0010","0011","0100","0101","0110","0111", //
	   "1000","1001","1010","1011","1100","1101","1110","1111")
	for(i=1;i<=cols(d);i++) {
		dd = d[i] :+ d
		b = b, dd
	}
	if( v>0 & v <= 255 & w > 0 & w <= 8) {	
		st_local("v" , b[v+1] )
		st_local("w", substr(b[v+1], w, 1))
	}
}
end

. mata: bit(128,1)

. di "`v' `w'"
10000000 1

. mata: bit(128,3)

. di "`v' `w'"
10000000 0


Kit Baum   |   Boston College Economics & DIW Berlin   |   http://ideas.repec.org/e/pba1.html
An Introduction to Stata Programming | http://www.stata-press.com/books/isp.html
   An Introduction to Modern Econometrics Using Stata  |   http://www.stata-press.com/books/imeus.html

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   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