I solved the problem but dont know how to post it in a good manner, so I edit this post and put the solution in the end of it.
Need help with following in C, trying to shift a bytes bits to reverse order.
I want Step1[] = {1,0,0,1,0,0,0,0}; to become {0,0,0,0,1,0,0,1}.
void Stepper(void)
{
static uint8_t Step1[] = {1,0,0,1,0,0,0,0};
BridgeControl(Step1);
}
void BridgeControl(unsigned char *value)
{
uint8_t tempValue;
uint8_t bit = 8;
uint8_t rev = 1;
if (rev) // CW otherwise CCW
{
tempValue = *value;
do{
if(tempValue) // Right-shift one
tempValue = 1 >> 1;
else
tempValue = 0 >> 1;
}while(--bit, bit);
*value = tempValue;
}
I know the bridcontrol is totally wrong, here i could need help!
Kind Regards
New code:
void BridgeControl(uint8_t *value)
{
// For example, initial value could be 1001000 then I
// would like the outcome to be 00001001
uint8_t tempValue;
uint8_t bit = 3;
uint8_t rev = 1;
if (rev) // CW otherwise CCW
{
tempValue = *value; //so... its 0b10010000
do{
tempValue >>=1; //1st this produce 01001000
tempValue = 0 >> 1; //1st this produce 0010 0100
//2nd time produce 0001 0010
//3d time produce 0000 1001
}while(--bit, bit);
*value = tempValue;
}
M1BHI = value[7];
M1BLI = value[6];
M1AHI = value[5];
M1ALI = value[4];
M2BHI = value[3];
M2BLI = value[2];
M2AHI = value[1];
M2ALI = value[0];
}
Solution:
void BridgeControl(uint8_t value)
{
uint8_t tempvalue[8];
uint8_t i = 8;
uint8_t cont;
cont = value;
do{
value = value >> i-1;
value = value & 1;
tempvalue[8-i] = value;
value = cont;
}while(--i,i);
M1BHI = tempvalue[7];
M1BLI = tempvalue[6];
M1AHI = tempvalue[5];
M1ALI = tempvalue[4];
M2BHI = tempvalue[3];
M2BLI = tempvalue[2];
M2AHI = tempvalue[1];
M2ALI = tempvalue[0];
}
If I want the reversed order of the bits in the array, just change tempvalue[8-i] to tempvalue[i-1].
Your variable names sounds like you are trying to work with hardware. So i guess you really want to shift bits in one byte variable and not in an int array.
This statment reverses the bits in a byte:
byte reversedVal = (byte) (val & 1 << 7
+ val & 2 << 5
+ val & 4 << 3
+ val & 8 << 1
+ val & 16 >> 1
+ val & 32 >> 3
+ val & 64 >> 5
+ val & 128 >> 7);
If you really want to reverse a int array you can use LINQs Reverse method as suggested by scottm but thats probably not the fastest option.
Easy-cheesy with Array.Reverse():
byte[] step1 = new {0,1,0,1};
var reversed = Array.Reverse(step1);
If you actually need to swap endianess, you can look at the answer here.
void BridgeControl(unsigned char values[], int size){
unsigned char *head, *end, wk;
for(head = values, end = values + size - 1; head < end; ++head, --end){
wk = *head;
*head = *end;
*end = wk;
}
}
void Stepper(void){
static unsigned char Step1[] = {1,0,0,1,0,0,0,0};
BridgeControl(Step1, sizeof(Step1));
}
// changed the parameter to suit the type of members of array
void BridgeControl(uint8_t *value)
{
uint8_t tempvalue;
// only need to loop till midway; consider the two sides as lateral images of each other from the center
for (int i=0; i < 8/2; i++)
{
// preserve the current value temporarily
tempvalue = *[value + i];
// set the current value with the value in the mirrored location
// (8th position is the mirror of 1st; 7th position is the mirror of 2nd and so on)
*[value + i] = *[value + (7 - i)];
// change the value in the mirrored location with the value stored temporarily
*[value + (7 - i)] = tempvalue;
}
}
// you may want to use sizeof(uint8_t) * (7 - i) instead of (7 - i) above
//Exempel of input going to function: int value = 0b10010000;
void BridgeControl(uint8_t value uint8_t dir)
{
uint8_t tempvalue[8];
uint8_t i = 8;
uint8_t cont;
cont = value;
if (dir){
do{
value = value >> i-1;
value = value & 1;
tempvalue[8-i] = value;
value = cont;
}while(--i,i);
}
else{
do{
value = value >> i-1;
value = value & 1;
tempvalue[i-1] = value;
value = cont;
}while(--i,i);
}
M1BHI = tempvalue[7];
M1BLI = tempvalue[6];
M1AHI = tempvalue[5];
M1ALI = tempvalue[4];
M2BHI = tempvalue[3];
M2BLI = tempvalue[2];
M2AHI = tempvalue[1];
M2ALI = tempvalue[0];
}
Related
I'm trying to make program that will for for example 273(000100010001b) make to 4095(111111111111b).
Funny part is that my program works for first 2 iterations, for example 17(00010001b) correctly returns 255(11111111b) but every byte after that doesn't work. For instance 273(000100010001b) returns 61951(1111000111111111b) and I cant figure out why is that.
Here is my code
int x,temp, i;
int mask = 15;
scanf_s("%d", &x);
temp = x;
for(i=0;i<4;i++){
mask<<=i*4;
if((temp&1)==1){
x|=mask;
} else{
}
temp>>=4;
}
printf("%d", x);
The issue is the shift you perform on mask. You shift it by 0 on the 1st iteration, 4 on the 2nd, 12 (4 + 8) on the 3rd and so on.
Also, you don't apply the mask over all the bits of temp. I can't tell if you do this on purpose.
Here you are a fixed version:
int foo(int x) {
/* ^ I didn't know how to call such function */
static size_t const mask_size = 4;
unsigned mask = 15;
int temp = x;
for (unsigned i = 0; i < (CHAR_BIT * sizeof(int)) / mask_size; ++i) {
if ((temp & 1) == 1) {
x |= mask;
}
mask <<= mask_size;
temp >>= mask_size;
}
return x;
}
My results are:
in: 17(10) = 10001(2)
out: 255(10) = 11111111(2)
in: 273(10) = 100010001(2)
out: 4095(10) = 111111111111(2)
in: 4369(10) = 1000100010001(2)
out: 65535(10) = 1111111111111111(2)
I could not found an answer with google so i went for it and programmed quite a few hours.
I want to save 9-bit values to eeprom without wasting the other 7 bits.
I save values that would be up to 500 and i have not much EEPROM left.
The same principle can be applied to arrays, which i did just to not waer down the EEPROM.
So I made this little program:
/*
* Write only a certain number of bits to EEPROM.
*
* keeps the other bit in the byte of the eeprom as they are.
*
* Working version with 9 bits:
* 2019-10-03 15:57
* 2019-10-03 22:09 tested with chars too
* 2019-10-04 08:25 works with 7 bit chars also!
* 2019-10-04 12:27 fixed the combining of oldByte and new values in writeBitsToEEPROM(), because chars like 'รถ' altered previous bit (left side) that should not have been altered.
*
*/
#include "arduino.h"
#include "EEPROM.h"
#include "math.h"
#define BIT_BLOCKS_COUNT 15
#define BLOCK_BYTE_COUNT 17
#define ARRAY_SIZE BLOCK_BYTE_COUNT+2
//TODO: change back to original value
#define EEPROM_SIZE ARRAY_SIZE
byte fakeEEPROM[ARRAY_SIZE] = {0};
String byteToString(byte value){
char byteChar[9];
byteChar[8] = '\0'; //we need a terminator
for(int i=7; i>=0; i--){
byteChar[7-i] = (value & (1 << i)) ? '1' : '0';
}
return String(byteChar);
}
String byteToString(unsigned long value, byte bytesToRead){
String str1 = byteToString(value >> 8);
String str2 = byteToString(value & 0xFF);
return str1 + " " + str2;
}
int globBlockStartAdress = 0;
byte globNumberOfBits = 0;
int globBlockSizeBytes = 0;
bool initBitBlock(int blockStartAdress, int blockCount, byte numberOfBits) {
globBlockStartAdress = blockStartAdress;
globNumberOfBits = numberOfBits;
// calc needed number of bytes and roud up
int tempBlockSize = blockCount * numberOfBits / 8;
if(blockCount * numberOfBits % 8)
tempBlockSize++;
// make number of bytes even
if(tempBlockSize % 2)
tempBlockSize++;
globBlockSizeBytes = tempBlockSize;
if(blockStartAdress + globBlockSizeBytes > EEPROM_SIZE)
return false;
return true;
}
/*
* Writes 1 to 9 bits to "internalAdress" within a designated block in eeprom
*/
void writeBitsToEEPROM(unsigned int bitsToBeWritten, int internalAdress){
//TODO: check if value is not higher than what can be stored
// if(bitsToBeWritten){
//
// }
int trueEEPROMAdress = globBlockStartAdress + internalAdress * globNumberOfBits / 8;
if(trueEEPROMAdress + 1 >= ARRAY_SIZE || internalAdress * globNumberOfBits / 8 >= globBlockSizeBytes){
Serial.print("globBlockSizeBytes: ");
Serial.println(globBlockSizeBytes);
Serial.println("FEHLER writeBitsToEEPROMWTF: ");
Serial.println(trueEEPROMAdress + 1);
Serial.println(internalAdress * globNumberOfBits / 8 );
}
byte startBitOfEEPROMByte = (internalAdress * globNumberOfBits) % 8;
unsigned int oldIntFromEEPROM = (fakeEEPROM[trueEEPROMAdress] << 8) | fakeEEPROM[trueEEPROMAdress + 1];
//Todo: change to eeprom
//filter out only the bits that need to be kept.
//EEPROM.get(trueEEPROMAdress, oldEEPROMByteBits);
// there might be bits in the byte that we dont want to change. left side and right side
unsigned int mask1KeepFromEEPROM = (0xFFFF << (16 - startBitOfEEPROMByte));
unsigned int mask2KeepFromEEPROM = (0xFFFF >> (startBitOfEEPROMByte + globNumberOfBits));
//if(16 - startBitOfEEPROMByte - numberOfBits > 0)
//mask2KeepFromEEPROM= (0xFFFF >> (startBitOfEEPROMByte + numberOfBits));
// masks combined
unsigned int maskIntToKeepFromEEPROM = mask1KeepFromEEPROM | mask2KeepFromEEPROM;
int newEEPROMInt = (oldIntFromEEPROM & maskIntToKeepFromEEPROM) | ((bitsToBeWritten << (16 - globNumberOfBits - startBitOfEEPROMByte) & ~maskIntToKeepFromEEPROM));
//Todo: change to eeprom
//write
//EEPROM.update(trueEEPROMAdress, newEEPROMByteBitsA);
fakeEEPROM[trueEEPROMAdress] = (newEEPROMInt >> 8);
fakeEEPROM[trueEEPROMAdress + 1] = (byte) newEEPROMInt;
if(trueEEPROMAdress + 1 > BLOCK_BYTE_COUNT){
Serial.println("FEHLER writeBitsToEEPROM");
Serial.println(trueEEPROMAdress + 1);
Serial.println("blockStartAdress");
Serial.println(globBlockStartAdress);
Serial.println("internalAdress");
Serial.println(internalAdress);
Serial.println("numberOfBits");
Serial.println(globNumberOfBits);
}
// Serial.print("trueEEPROMAdress: ");
// Serial.println(trueEEPROMAdress);
//
// Serial.print("internalAdress: ");
// Serial.println(internalAdress);
//
// Serial.print("globNumberOfBits: ");
// Serial.println(globNumberOfBits);
//
// Serial.print("bitsToBeWritten: ");
// Serial.println(byteToString(bitsToBeWritten,2));
//
// Serial.print(" mask1KeepFromEEPROM: ");
// Serial.println(byteToString(mask1KeepFromEEPROM,2));
//
// Serial.print("mask2KeepFromEEPROM: ");
// Serial.println(byteToString(mask2KeepFromEEPROM,2));
//
// Serial.print("maskIntToKeepFromEEPROM: ");
// Serial.println(byteToString(maskIntToKeepFromEEPROM,2));
//
// Serial.print("oldIntFromEEPROM: ");
// Serial.println(byteToString(oldIntFromEEPROM,2));
//
// Serial.print("newEEPROMInt: ");
// Serial.println(byteToString(newEEPROMInt,2));
//
// Serial.print("512: ");
// Serial.println(byteToString(512, 2));
//
// Serial.print("65535: ");
// Serial.println(byteToString(65535, 2));
}
unsigned int ReadBitsFromEEPROM(int internalAdress){
int trueEEPROMAdress = globBlockStartAdress + internalAdress * globNumberOfBits / 8;
byte startBitOfEEPROMByte = (internalAdress * globNumberOfBits) % 8;
if(trueEEPROMAdress + 1 > BLOCK_BYTE_COUNT)
Serial.println("FEHLER readBits");
unsigned int oldIntFromEEPROM = (fakeEEPROM[trueEEPROMAdress] << 8) | fakeEEPROM[trueEEPROMAdress + 1];
//Todo: change to eeprom
//filter out only the bits that need to be kept.
//EEPROM.get(trueEEPROMAdress, oldEEPROMByteBits);
unsigned int mask1KeepFromEEPROM = (0xFFFF << (16 - startBitOfEEPROMByte));
unsigned int mask2KeepFromEEPROM = (0xFFFF >> (startBitOfEEPROMByte + globNumberOfBits));
unsigned int maskIntToKeepFromEEPROM = mask1KeepFromEEPROM | mask2KeepFromEEPROM;
unsigned int valueFromEEPROM = ~maskIntToKeepFromEEPROM & oldIntFromEEPROM;
// Serial.print("trueEEPROMAdress: ");
// Serial.println(trueEEPROMAdress);
//
// Serial.print("internalAdress: ");
// Serial.println(internalAdress);
//
// Serial.print("numberOfBits: ");
// Serial.println(numberOfBits);
//
// Serial.print(" mask1KeepFromEEPROM: ");
// Serial.println(byteToString(mask1KeepFromEEPROM,2));
//
// Serial.print("mask2KeepFromEEPROM: ");
// Serial.println(byteToString(mask2KeepFromEEPROM,2));
////
// Serial.print("maskIntToKeepFromEEPROM: ");
// Serial.println(byteToString(maskIntToKeepFromEEPROM,2));
////
// Serial.print("oldIntFromEEPROM: ");
// Serial.println(byteToString(oldIntFromEEPROM,2));
return (valueFromEEPROM >> (16 - globNumberOfBits - startBitOfEEPROMByte));
}
void setup() {
Serial.begin(57600);
Serial.print(F("\n# Programversion: "));
Serial.print(__TIME__);
Serial.print(" ");
Serial.println(__DATE__);
Serial.println("Setup finished");
delay(1000);
}
void printEEPROM(){
for(int i = 0; i < ARRAY_SIZE; i++){
byte b;
//Todo: change to eeprom
//EEPROM.get(i, b);
b = fakeEEPROM[i];
Serial.print(byteToString(b));
Serial.print(" ");
}
Serial.println();
}
void testNumbers() {
Serial.println("bits?");
while( ! Serial.available());
String input = Serial.readString();
unsigned int value = input.toInt();
initBitBlock(1, 15, 9);
// Serial.print("value: ");
// Serial.println(byteToString(value));
for(int i = 0; i < BIT_BLOCKS_COUNT;i++){
for(int j = 0; j < BLOCK_BYTE_COUNT; j++){
fakeEEPROM[j] = 0xFF;
if(j > BLOCK_BYTE_COUNT)
Serial.println("FEHLER testNumbers");
}
// Serial.print("EEPROM before: ");
// printEEPROM();
writeBitsToEEPROM(value, i);
Serial.print("Returned: ");
Serial.println(ReadBitsFromEEPROM(i));
// Serial.print("EEPROM after: ");
// printEEPROM();
// Serial.println();
}
delay(1000);
}
#define CHAR_COUNT 16
void testChars() {
// Serial.println("bits?");
// while( ! Serial.available());
// String input = Serial.readString();
//
// unsigned int value = input.toInt();
initBitBlock(1, CHAR_COUNT, 7);
Serial.println("string?");
while( ! Serial.available());
String input = Serial.readString();
Serial.println(input);
char testString[CHAR_COUNT] = {'\0'};
input.toCharArray(testString, CHAR_COUNT, 0);
for(int j = 0; j < ARRAY_SIZE; j++){
fakeEEPROM[j] = 0;//xFF;
}
for(int i = 0; i < CHAR_COUNT; i++){
Serial.print("EEPROM before: ");
printEEPROM();
writeBitsToEEPROM(testString[i], i);
Serial.print("EEPROM after: ");
printEEPROM();
Serial.println();
}
Serial.println("Returned: ");
for(int i = 0; i < CHAR_COUNT; i++){
Serial.print((char) ReadBitsFromEEPROM(i));
}
Serial.println();
delay(1000);
}
void loop(){
testChars();
testNumbers();
}
which of course it not complete. Its just for saving those 9-bit values.
My question is: Has anyone else programmed a function like this - or knows where to find this - that is not limited to 9 bits (10 bits will span over 3 bytes)?
This function should take the number of bits given by bitsPerVal from each value in the input array pVals and pack them into the byte array pointed to by pOutBytes:
#include <stdint.h>
void pack_bits(uint32_t *pVals, size_t numVals, int bitsPerVal, uint8_t *pOutBytes)
{
uint32_t mask = ~(UINT32_MAX << bitsPerVal);
int outBitsLeft = 8;
int inBitsLeft = bitsPerVal;
while(numVals > 0)
{
if(inBitsLeft > outBitsLeft)
{
inBitsLeft -= outBitsLeft;
*pOutBytes |= (*pVals & mask) >> inBitsLeft;
mask >>= outBitsLeft;
outBitsLeft = 0;
}
else
{
outBitsLeft -= inBitsLeft;
*pOutBytes |= (*pVals & mask) << outBitsLeft;
mask = ~(UINT32_MAX << bitsPerVal);
inBitsLeft = bitsPerVal;
--numVals;
++pVals;
}
if(0 == outBitsLeft)
{
outBitsLeft = 8;
++pOutBytes;
}
}
}
The array pointed to by pOutBytes must suitably sized (ie ((numVals*bitsPerVal) + 7) / 8) and initialised to zero before calling. You can write it to your EEPROM after.
Hopefully this works well, I have done much testing on it though.
Here is an example of how 10 bits (actually 16-bits when written...) from 2 different fields could write to 16-bits of output.
struct EEPROM_Output
{
uint16_t a : 9; // 0 - 511 can be stored here
uint16_t b : 1; // 0 or 1 here.
uint16_t pad : 6; // Future use - we place this here to make it obvious that there are bits remaining.
};
void foo()
{
struct EEPROM_Output save;
save.a = 100;
save.b = 1;
WriteToEEPROM(&save, sizeof(save));
}
I am writing a routine in C, targeted for an embedded platform.In the routine I need to perform bitwise XOR and SHIFT RIGHT operations on 128-bit values. The target arch doesn't have SSE2, hence no native 128-bit operations supported. I came across this answer which simulates the SHIFT operations in software.
My question is, are there better ways of doing this, I mean with better data structure to represent 128-bit values and optimal way to simulate the SHIFT and XOR operations than using recursion(as done in the answer in the link). I wish to minimise usage of the limited stack memory.
You can use a structure to store 128 bit data as follows
typedef struct
{
uint32_t a;
uint32_t b;
uint32_t c;
uint32_t d;
} Type_128bit;
Then you can write a left shift function as follows
int leftshift(Type_128bit in, Type_128bit out, int value)
{
int val;
if (value >= 128)
{
return (-1); // error condition
}
else if (value < 32)
{
out->a = (in->a << value) | (in->b >> value);
out->b = (in->b << value) | (in->c >> value);
out->c = (in->c << value) | (in->d >> value);
out->d = in->d << value;
}
else if (value < 64)
{
val = value - 32;
out->a = (in->b << val) | (in->c >> val);
out->b = (in->c << val) | (in->d >> val);
out->c = (in->d << val);
out->d = 0x00;
}
else if (value < 96)
{
val = value - 64;
out->a = (in->c << val) | (in->d >> val);
out->b = (in->d << val);
out->c = 0x00;
out->d = 0x00;
}
else // value < 128
{
val = value - 96;
out->a = (in->d << val);
out->b = 0x00;
out->c = 0x00;
out->d = 0x00;
}
return (0); //success
}
This will avoid the recursion of the mentioned solution and give better runtime. But code size will increase and you need to carefully test the code.
uint32_t *shiftL(uint32_t *val, const size_t size, const size_t nbits) // <= 32
{
uint32_t mask = (1 << nbits) - 1;
mask <<= 32 - nbits;
for(size_t cword = size; cword - 1 ; cword --)
{
uint32_t temp = (val[cword - 2] & mask) >> nbits
val[cword - 1] <<= nbits;
val |= temp;
}
val[0] <<= nbits;
return val;
}
I'm trying to implement a FAT12 file system in which there's a FAT table data structure which is an unsigned char array. I need to write a function which given an array index would write a value to the next 12 bits (because it's FAT12) which is quite tricky because part of the value needs to go to one byte and the other part needs to go the half of the second byte.
This is the get value function I came up with:
//FAT is the unsigned char array
int GetFatEntry(int FATindex, unsigned char * FAT) {
unsigned int FATEntryCode; // The return value
// Calculate the offset of the WORD to get
int FatOffset = ((FATindex * 3) / 2);
if (FATindex % 2 == 1){ // If the index is odd
FATEntryCode = ((unsigned char)(&FAT[FatOffset])[0] + (((unsigned char)(&FAT[FatOffset])[1]) << 8));
FATEntryCode >>= 4; // Extract the high-order 12 bits
}
else{ // If the index is even
FATEntryCode = ((unsigned char)(&FAT[FatOffset])[0] + (((unsigned char)(&FAT[FatOffset])[1]) << 8));
FATEntryCode &= 0x0fff; // Extract the low-order 12 bits
}
return FATEntryCode;
}
I'm struggling to come up with the function which would set a value given a FATindex. I would appreciate any suggestions.
This seems to work. The data that should be written should be in the first 12 bits of data
void WriteFatEntry(int FATindex, unsigned char * FAT, unsigned char data[2]) {
// Calculate the offset of the WORD to get
int FatOffset = ((FATindex * 3) / 2);
unsigned char d;
if (FATindex % 2 != 0){ // If the index is odd
// Copy from data to d and e, and shift everything so that second half of
// e contains first half of data[1], and first half of e contains second
// half of data[0], while second half of d contains first half of data[0].
// First half of d contains a copy of first four bits in FAT[FatOffset]
// so that nothing changes when it gets written
unsigned char e=data[1];
e>>=4;
d=data[0];
e|=(d<<4) & 0b11110000;
d>>=4;
d |= FAT[FatOffset] & 0b11110000;
FAT[FatOffset]=d;
FAT[FatOffset+1] = e;
}
else{ // If the index is even
d = data[1] & 0b11110000;
d |= FAT[FatOffset+1] & 0b00001111;
FAT[FatOffset] = data[0];
FAT[FatOffset+1] = d;
}
}
#include <stdio.h>
#if 1 /* assuming MSB first */
#define MSB (idx)
#define LSB (idx+1)
#else /* assuming LSB first */
#define MSB (idx+1)
#define LSB (idx)
#endif
unsigned fat_getval(unsigned char * tab, unsigned num)
{
unsigned idx;
unsigned val;
idx = num + num/2;
val = (tab[MSB] <<8 ) + (tab[idx+1] ) ;
if (num %2 ==0) val >>= 4;
return val & 0xfff;
}
void fat_putval(unsigned char * tab, unsigned slot, unsigned val)
{
unsigned idx;
idx = slot + slot/2;
if (slot %2 ==0) { /* xyz_ */
val <<= 4;
val |= tab[LSB] & 0xf;
}
else { /* _xyz */
val |= (tab[MSB] & 0xf0) << 8;
}
tab[MSB] = val >>8;
tab[LSB] = val &0xff;
}
#undef MSB
#undef LSB
unsigned char fattable[] = "\x01\x23\x45\x67\x89\xab"; // 12 nibbles
int main(void)
{
unsigned idx, ret;
for (idx = 0; idx < 6; idx++) { // 6 bytes -> 12 nibbles */
printf(" %02x", fattable[idx] );
}
printf("\n");
printf("Put(0,0xabc):\n");
fat_putval(fattable, 0, 0xabc);
for (idx = 0; idx < 6; idx++) {
printf(" %02x", fattable[idx] );
}
printf("\n");
printf("Put(3,0xdef):\n");
fat_putval(fattable, 3, 0xdef);
for (idx = 0; idx < 6; idx++) {
printf(" %02x", fattable[idx] );
}
printf("\n");
printf("Get(0 to 4):\n");
for (idx = 0; idx < 4; idx++) { // 12 / 3 ~> 4 * 12bit entries
ret = fat_getval( fattable, idx);
printf("%u := %x\n", idx, ret );
}
printf("\n");
return 0;
}
I am trying to set a bit in a 8 bit variable.
Every time I print the variable after setting a particular bit , I always get the value as 1.
uint8 value;
value = (1<<1 || value)
printf(%x \n,value); //prints 1 instead of 2
value = (1<<2 || value)
printf(%x \n,value); //prints 1 instead of 4
You're using boolean 'or' ||. Bitwise 'or' is |.
Also you haven't initialized value so you can't expect it to be anything.
No you don't do it like that.
To set a bit you OR with 1.
For example to set the least significant bit you OR with 1.
ie:
unsigned char val = 4;
// set bit 0
val |= 1;
printf("Value now: %x\n", val);
To set bit 1:
unsigned char val = 4;
// set bit 1
val |= 1 << 1;
printf("Value now: %x\n", val);
A complete example
#include <stdio.h>
char* get_binary(unsigned char buffer, char* binary) {
for (int i = 0; i < 8; ++i) {
int bit = (buffer >> i) & 1;
binary[7 - i] = bit ? '1' : '0';
}
return binary;
}
int main() {
unsigned char val = 4; // val now 100
int bits_to_shift;
unsigned char buffer[10] = { 0 };
unsigned char* p = buffer;
// set bit 0
val |= 1;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now 5 :- 101
// To set bit 1 (ie set so we have 111), shift to position then OR
// set bit 1
bits_to_shift = 1;
val |= 1 << bits_to_shift;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now 7 :- 111
// set bit 3
bits_to_shift = 3;
val |= 1 << bits_to_shift;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now F :- 1111
}