0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C > ビット演算 > sizedCopy_shifted() > MSBの位置を指定してコピー

Last updated at Posted at 2015-11-04

http://qiita.com/7of9/items/4659da725d849eaf6b44
の続き

以下の指定をして変数から変数へ数値をコピーしたい

  • コピーする数値の桁数指定 (例: 3桁)
  • コピーする数値のMSB位置指定
    • コピー先のビットサイズ指定

# include <stdio.h>

void sizedCopy_shifted(int srcSize, int srcVal, int dstMSB, int dstSize, unsigned long *dstPtr)
{
	// dstMSB : [0..] index of dst MSB
	
	unsigned long mask = (1u << srcSize) - 1;
	int lsbPos = dstMSB + srcSize - 1; // LSB position of the srcVal
	int shift = dstSize - lsbPos - 1;
	unsigned long workVal;
	
	mask = (mask << shift);
	workVal = (srcVal << shift);
	*dstPtr &= ~mask;
	*dstPtr |= (workVal & mask);
}

int main(void) {
	unsigned long ulval = 0;

	//            srcSize, srcVal, dstMSB, dstSize, *dstPtr
	sizedCopy_shifted(3, 0x5, /* dstMSB=*/6, 10, &ulval); // to 0x0A
	sizedCopy_shifted(3, 0x4, /* dstMSB=*/3, 10, &ulval); // to 0x4A
	sizedCopy_shifted(3, 0x3, /* dstMSB=*/0, 10, &ulval); // to 0x1CA

	printf("0x%X", ulval);
	return 0;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?