Created
August 14, 2012 14:20
-
-
Save ryochack/3349678 to your computer and use it in GitHub Desktop.
BitOrder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct tag_RegisterBlock { | |
unsigned char addr; | |
int sbit; | |
int len; | |
} TRegisterBlock; | |
static inline void dec2bin(unsigned char val) | |
{ | |
char binstr[9] = ""; | |
binstr[8] = '\0'; | |
int i; | |
for (i=7; i>=0; i--) { | |
binstr[i] = (val & 0x01) ? ('1') : ('0'); | |
val >>= 1; | |
} | |
printf("%s ", binstr); | |
} | |
static inline void setreg(const TRegisterBlock *reg, const unsigned int data) | |
{ | |
const int QUOTIENT = reg->sbit >> 3; | |
unsigned int addr = reg->addr + QUOTIENT; | |
int sft = reg->sbit - QUOTIENT*8; | |
int sz = reg->len; | |
unsigned int d = data << sft; | |
unsigned char map[4] = {0xFF, 0xFF, 0xFF, 0xFF}; | |
{ | |
int i; | |
printf("\n-> map: "); | |
for (i=3; i>=0; i--) { printf("%02X ", map[i]); } | |
printf("\n"); | |
} | |
while (sz > 0) { | |
unsigned char mask = (~(0xFF << sz)) << sft; | |
printf("0x%02X | 0x%02X, d=0x%02X:mask=0x%02X\n", (map[addr] & ~mask), (d & mask), d, mask); | |
map[addr] = (map[addr] & ~mask) | (d & mask); | |
printf("map[%d]=%02X\t(sft=%2d, sz=%2d, d=0x%08X, mask=0x%02X)\n", addr, map[addr], sft, sz, d, mask); | |
sz -= (8 - sft); | |
sft = 0; | |
addr++; | |
d >>= 8; | |
} | |
{ | |
int i; | |
printf("\n-> map: "); | |
for (i=3; i>=0; i--) { printf("%02X ", map[i]); } | |
printf("\n\n"); | |
printf("MSB --------------------------- LSB\n"); | |
for (i=3; i>=0; i--) { dec2bin(map[i]); } | |
printf("\n"); | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc < 4) { | |
printf("require 3 argments. startbit, length, data.\n"); | |
return -1; | |
} | |
const TRegisterBlock reg = { | |
.addr = 0, | |
.sbit = (int)atoi(argv[1]), | |
.len = (int)atoi(argv[2]), | |
}; | |
const unsigned int data = strtoul(argv[3], NULL, 0); | |
setreg(®, data); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
./a.out $STARTBIT $BITLENGTH $SETDATA