Hello :)

i need to write a program which gets from user number and index
( 0 <= number <= 255 , 0<=index<=7) .
then to add up to the number in bitwise a 1 in the place of the index :
if number is 102 which is 01100110
and index is 4 which is 01110110
and get 118 as a result.

for some reason it doesnt do that ..... i have no idea why , i used OR operation between numbers ..... :rolleyes:

Code added

thanx , Yotam

Dani AI

Generated

Short summary: set a single bit by building a mask (a 1 in the picked position) and applying a bitwise OR to the original byte. Index 0 is the least‑significant bit; index 7 is the MSB. For the example in the thread (102 -> set bit 4 -> 118) the mask has a 1 in position 4 and all other bits 0.

Notes and common pitfalls mentioned in the thread

  • demonstrated shifting to build the mask; that approach is correct. Prefer a bitwise OR to set a bit instead of adding the mask — addition can carry into higher bits if the bit is already set.
  • used pow(), and also added 1 to the index; avoid pow() for bit work: it returns a floating value, can introduce rounding and overhead, and leads to off‑by‑one mistakes.
  • A very common bug is using logical OR (||) instead of bitwise OR (|). || yields 0 or 1, so the result becomes 0/1 instead of the intended byte. Another gotcha is using a signed char and then printing with %d — values above 127 may appear negative.

Robust approach (validate + use unsigned types)

  • Validate index is 0..7.
  • Use an unsigned 8‑bit type (e.g., uint8_t) or an unsigned int for the mask to avoid sign/overflow surprises.
  • Build the mask, set the bit with bitwise OR, and print/cast as unsigned when using printf.

Example (safe, minimal):

#include <stdio.h>
#include <stdint.h>

int main(void) {
    unsigned in; unsigned idx;
    if (scanf("%u %u", &in, &idx) != 2 || idx > 7) return 1;
    uint8_t n = (uint8_t)in;
    uint8_t mask = (uint8_t)(1u << idx);
    n |= mask;
    printf("%u\n", (unsigned)n);
    return 0;
}

Quick checklist: check for || vs |, ensure index range, prefer unsigned types, and avoid pow() for bit fiddling.

Recommended Answers

All 4 Replies

102 (decimal) = 1100110 (binary)
1 left shifted 4 is 10000 (binary)

1100110 (binary)
+ 10000 (binary)
-------
1110110 (binary) = 118 decimal

If I understand you.

#include <stdio.h>

int main(void)
{
   int number = 102, index = 4;
   number += 1 << index;
   printf("number = %d\n", number);
   return 0;
}

/* my output
number = 118
*/

that code is actually adding 1 in place of index ?

ch2=pow(2,index + 1);

Why did you add 1 to the index? - 32 (2^5) in binary is 00100000 - The code would give your expected result without that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.