Skip to content

Instantly share code, notes, and snippets.

@P-A-R-U-S
Last active June 15, 2020 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save P-A-R-U-S/e8d738d84424272f6fa2437b6de17898 to your computer and use it in GitHub Desktop.
Save P-A-R-U-S/e8d738d84424272f6fa2437b6de17898 to your computer and use it in GitHub Desktop.
Insertion M into N from bit "i" to "j"
package Part_5
import "testing"
/*
Insertion: You are given two 32-bit numbers, N and M, and two bit positions, i and j.
Write a method to insert M into N such that M starts at bit j and ends at bit i.
You can assume that the bits j through i have enough space to fit all of M.
That is, if M= 10011, you can assume that there are at least 5 bits between j and i.
You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2.
EXAMPLE #1
Input:
N = 10000000000, i 2, j 6
M= 10011
Output: N= 10001001100
EXAMPLE #2
Input:
N = 10000110000, i 2, j 6
M= 10011
Output: N= 10001001100
Hints: # 137, #169, #215
*/
/*
Даны два 32-разрядных числа N и М и две позиции битов i и j . Напишите мeтод для вставки М в N так,
чтобы число М занимало позицию с бита j по бит i. Предполагается, что j и i имеют такие значения, что число М гарантированно
поместится в этот промежуток.
Скажем, для м = 10011 можно считать, что j и i разделены как минимум 5 битами.
Комбинация вида j =З и i =2 невоз­ можна, так как числом не поместится между битом 3 и битом 2.
*/
func insertionMintoN(N, M uint32, i, j int) uint32 {
mask := uint32(1 << i)
for p:=i; p<j; p++ {
mask = mask | mask << 1
}
return N & ^mask | M << i
}
func Test_Insertion_M_into_N(t *testing.T) {
r1 := insertionMintoN(0x400, 0x13, 2,6)
if r1 != 0x44C {
t.Fail()
}
r2 := insertionMintoN(0x430, 0x13, 2,6)
if r2 != 0x44C {
t.Fail()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment