2
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 1 year has passed since last update.

6809にもあるエッチな名前の符号拡張をCで書いてみた

Last updated at Posted at 2020-05-18

モトローラの8bitCPU 6809にはSEXという命令があります。
Sign EXtensionの略で、「8ビットアキュームレーター(B)の内容を符号付きで16ビットに拡張し、上位A、下位Bレジスターとして16ビットに連結したアキュームレーター(D)に格納する。」というものです。OPコードは0x1Dです。

任意ビットで符号拡張するコードをCで書いてみました。
2進数nbit(1<=n<=63)の数を64bitに、符号付き拡張をします。

Ver 1.1 fujitanozomu氏による指摘で、nビットを超える数が、a,bに与えられた場合を考慮して書き換え。

sex.c
/*
   SEX Sign EXtend
   符号拡張
 */

#include    <stdio.h>

/* long sex(long a,int bitn)
 * input:  bitn 何ビット目で符号拡張するか
 *         a    被演算数
 *
 * output: 符号拡張された結果
 *
 */
long sex(long a,int bitn) {
    unsigned long p=-1;
    long r;

    r=(a&~(p<<bitn))|(a>>(bitn-1)&1?p<<bitn:0);

    return(r);
}

int main()
{
    long a=0xc0ffee;     /* 24 bit の負の値 */
    long b=0x7fffff;     /* 24 bit の正の値 */
    long r1,r2;          /* 結果を格納する変数 */

    r1 = sex(a,24);
    r2 = sex(b,24);
    printf("%ld %ld %016lx %016lx\n",a,r1,a,r1);
    printf("%ld %ld %016lx %016lx\n",b,r2,b,r2);
}

実行結果

12648430 -4128786 0000000000c0ffee ffffffffffc0ffee
8388607 8388607 00000000007fffff 00000000007fffff
2
0
2

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
2
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?