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

st: RE: re: return a specific bit from integer variable

From   "Nick Cox" <>
To   <>
Subject   st: RE: re: return a specific bit from integer variable
Date   Mon, 5 Oct 2009 12:47:52 +0100

See also 

1. official command -inbase-. 

2. -egen- function -base()- in -egenmore- from SSC. The help gives an
example that seems parallel to Steinar's problem. 

Note that -split- (as suggested by Martin Weiss) is no help here.
-split- is for strings subdivided by parsing or punctuation characters. 


Kit Baum

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
void bit(real scalar v, real scalar w)
	string vector d, b
	d=("0000","0001","0010","0011","0100","0101","0110","0111", //
	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))

. mata: bit(128,1)

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

. mata: bit(128,3)

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

Steinar Fossedal

I have imported an 8-bit integer variable where each bit represents a
flag telling me if some property of the observation is true or false.

E.g. the number 8 in binary format is 00001000, while 10 would be
00001010. Bit nr. 4 from the left tells me if a car is delivered or not,
while the second to the right tells me if it's paid or not. So 8 = car
is delivered but not paid, 2 = paid but not delivered, 10 = paid and
delivered, etc.

I need to split this information into 8 dummyvariables so they can be
used to segment my data.

Does there exist a fairly smooth way to do this in Stata?

*   For searches and help try:

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