NguyenTam
NguyenTam

Reputation: 9

How to use bitwise to convert a 4-bit binary number to an 8-bit binary number?


My goal is to write a bitwise expression to represent an 8-bit number in the right column by a 4-bit number in the left column. Hope someone will help me to solve this question. Thanks very much!

4 bits         8 bits
0001         00000011
0010         00001100
0011         00001111
0100         00110000
0101         00110011
0110         00111100
0111         00111111
1000         11000000
1001         11000011
1010         11001100
1011         11001111
1100         11110000
1101         11110011
1110         11111100
1111         11111111

Upvotes: 0

Views: 1322

Answers (2)

user652038
user652038

Reputation:

If you create a type and implement what's necessary for MutableCollection, and RandomAccessCollection, then you can use Sequence's reduce.

0b1001.afterMitosis // 0b11_00_00_11
extension FixedWidthInteger where Self: _ExpressibleByBuiltinIntegerLiteral {
  var afterMitosis: Self {
    bits.enumerated().prefix(4).reduce(0) {
      let clonedBitPair = $1.element | $1.element << 1
      return $0 | clonedBitPair << ($1.offset * 2)
    }
  }
}
public extension FixedWidthInteger where Self: _ExpressibleByBuiltinIntegerLiteral {
  var bits: Bits<Self> {
    get { .init(integer: self) }
    set { self = newValue.integer }
  }
}

/// The bits of an integer, from least significant to most.
public struct Bits<Integer: FixedWidthInteger & _ExpressibleByBuiltinIntegerLiteral> {
  public var integer: Integer
}

// MARK: - MutableCollection, RandomAccessCollection
extension Bits: MutableCollection, RandomAccessCollection {
  public typealias Index = Int

  public var startIndex: Index { 0 }
  public var endIndex: Index { Integer.bitWidth }

  public subscript(index: Index) -> Integer {
    get { integer >> index & 1 }
    set {
      integer &= ~(1 << index)
      integer |= (newValue & 1) << index
    }
  }
}

Upvotes: 0

Falk H&#252;ffner
Falk H&#252;ffner

Reputation: 5040

The straightforward way is from a 4-bit word dcba to first generate 0d0c0b0a by shifting each bit in the right place:

t = (x & 0b0001) | ((x & 0b0010) << 1) | ((x & 0b0100) << 2) | ((x & 0b1000) << 3)

and then duplicate the bits:

return t | (t << 1)

A trickier alternative that needs fewer instructions is to first introduce a gap that leaves a and c in the right place:

t = (x | (x << 2)) & 0b00110011

and then shift b and d and introduce the duplication:

return ((t + (t | 0b1010101)) ^ 0b1010101) & 0b11111111

(the final & is not needed if the data type is limited to 8 bits anyway).

Upvotes: 1

Related Questions