Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I got stuck with my code, tried anything on this side and many other things Google showed.
To the problem:
I try to convert some code-snips from C# to phyton, but on this special point i got stuck.
public static long decode(string data, int size, int offset = 0)
{
long value = 0;
for (int i = 0; i < size; ++i) {
value <<= 6;
value |= (long)data[offset + i] - 0x30;
}
return value;
}
The String Data could be something like 1Dh. Based on this I convert each char to the hex-equivalent: 0x31, 0x44, 0x68 and subtract 0x30; so I get 0x1, 0x14, 0x38;
In the next step I have to convert to the binary equivalent 000001, 010100, 111000 and merge this to
000001010100111000. From this I want to get the integer meaning, in this case 5432.
Is there a possibility to do this in a smart and easy way in python?
It's actually pretty easy, and the translation is pretty straight forward. You can continue to use your bit shifting. The only change is the syntax of for-loop and using ord() to get the integer value from a character.
def decode(data, size, offset=0):
value = 0
for ch in data[offset:size]:
value <<= 6
value |= ord(ch) - 0x30
return value
Running this in the interpreter, I get 5432:
>>> decode("1Dh", 3)
5432
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
using c#
the float value i need to read
= 24.500000
when i try to read i get this result
= 1103364096
what conversion should i do to get the real value? i need help on this.
my failed attempts:
int data_1 = 1103364096;
UInt16 value = (UInt16)x;
ushort data_2= (ushort)(1103364096 & ((1 << 16) - 1));
int r = 1103364096;
short trimmed = unchecked((short)r);
these don't work!
As suggested by Jeremy, you need to use BitConverter.
We'll first get the byte representation of the integer i, then interpret those bytes as a float:
int i = 1103364096;
byte[] b = BitConverter.GetBytes(i);
float f = BitConverter.ToSingle(b, 0);
Console.WriteLine(f); // outputs 24.5
Try it online
Use Convert.ToFloat(x) to convert (from anything) to a float.
Use Convert.ToInt32(x) to convert (from anything) to an Int32.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to convert following C++ code to C#, but I do not understand what the sscanf_s function does in this example or what its C# equivalent is.
int i, Len, iHex;
UCHAR Buf[20];
CString sHex;
CString Key = "abc";
Len = Key.GetLength() >> 1;
for(i = 0; i < Len; i++) {
sHex = sDesKey.Mid(i * 2, 2);
sscanf_s(sHex, _T("%x"), &iHex);
Buf[i] = ~iHex;
}
If I understand the function of sscanf_s correctly from Martin Bonner's explanation, you are looking for how to convert a string that represents hexadecimal digits into an int. You can do so with the following:
iHex = Convert.ToInt32(sHex, 16);
This being said, whether or not you want to actually use int for your conversion result depends on how you are implementing the rest of that function. (Not all ints are created equal across languages.)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to read a file (>150 mb) and I need to read the binary representation of that file.
The file type is a .MP4.
I am trying to use this:
string.Join("-", x.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
but the problems are:
1) It is too slow
2) It uses a lot of RAMs memory
If I read the raw bytes with
File.ReadAllBytes(path);
How Can I do that without having to convert the file into a string (method below)?
When working with big files like in your case, it would be better to just view a small part of the file (It's not like you can show the entire file at once anyhow).
Some Streams (like the FileStream) have the ability to Seek a certain position, which you can use to set your starting position.
if(position > _stream.Length)
throw new IndexOutOfRangeException();
if (position + length > _stream.Length)
length = (int) (_stream.Length - position);
_stream.Seek(position, SeekOrigin.Begin);
_stream.Read(buffer, 0, length);
The conversion to binary isn't that hard eiter, depending on the bit order you want, you'll probably have to reverse this (this is highest bit left 1 = 00000001). To gain some performance when building the string, use a StringBuilder instead of just concating strings with += or +.
public string ToBinary(byte value)
{
string result = "";
for (int i = 0; i < 8; i++)
{
result = value%2 + result;
value /= 2;
}
return result;
}
private string ToBinary(byte[] values)
{
StringBuilder builder = new StringBuilder();
int column = 0;
foreach (byte value in values)
{
builder.Append(ToBinary(value) + " ");
column++;
if (column == 8)
{
builder.AppendLine();
column = 0;
}
}
return builder.ToString();
}
Can can then eiter use it in a console application
https://dotnetfiddle.net/GVLm27
or put those two together with a TextBox and a ScrollBar and you have a good starting point:
ong position = (long) scrollBar1.Value;
byte[] data = new byte[128];
_file.GetSection(data, position, data.Length);
textBox1.Text = ToBinary(data);
After all those comments on your question I hope the original title is still what you are after
C# Fastest way to read binary representation of data
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to write code in C# to build table that converts each UNICODE code to RGB color value.
I use UTF-16.
this table has three columns one for char or symbol or digit, another column for it's UNICODE code and last column for one of the 16 million colors
Can anyone suggest an easy way to do this???
If you ignore combining characters and such, then each Unicode code point is 16 bits. RGB is a 24-bit space that uses one byte for red, one byte for green, and one byte for blue. Obviously you can't do that with a 16-bit code. So what you do is use, for example 5 bits for red, 5 bits for green, and 6 bits for blue. Here's one way to do it.
Say you're given a string:
const string foo = "Hello, world.";
// rrrr rggg ggbb bbbb
const int RedMask = 0xF8;
const int GreenMask = 0xF8;
const int BlueMask = 0xFC;
const int RedShift = 8;
const int GreenShift = 3;
const int BlueShift = 2;
foreach (var c in foo)
{
int val = c;
int r = (val >> RedShift) & RedMask;
int g = (val >> GreenShift) & GreenMask;
int b = (val << BlueShift) & BlueMask;
// now create a color
Color clr = Color.FromArgb(r, g, b);
// and do something with it.
}
This code uses the high 5 bits (6 bits for blue) for each color, which will give a bit more differentiation than if you use the low bits.
Nothing forces you to use 5,5,6 as I did. You could make it 5,6,5 or 6,5,5, or 3,8,5, or whatever combination of r/g/b you want. All you have to do is change the shifts and offsets.
That said, for typical English text, the colors will be very similar. You can do other interesting things, although they'll take a bit more work. For example, you could make the blue component be a combination of bits 0, 3, 6, 9, 12, and 15. Green would be bits 1, 4, 7, 10, and 13. Red would be bits 2, 5, 8, 11, and 14. That would differentiate characters that are very close together.
The idea, though, remains the same: pick specific bits from the Unicode value and use them to construct the red, green, and blue components.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 14 years ago.
Improve this question
I was looking at the System.Net Namespace and it has an IPAddress instance you can use. This has a Parse method which you can use to parse a string into an IPInstance then use the Address property to give you the long value.
However...
The number returned is NOT the true conversion.
e.g. For IP 58.0.0.0 , the System.Net namespace gives me a value of 58...
When in fact, the integer value should be 973078528
Can someone please show me the correct code do convert this?
The formula should be.. (for ip 192.1.20.10).
192 * (256*256*256) + 1 * (256*256) + 20 * (256) + 10
The reason this formula is correct is that the number it returns you can use in a >= and <= query to determine an IP address that falls within a range.
The Address Property (of the IPAddress instance) does not calculate/return this. A bonus point for anyone that knows why the address property does not return what I think is the correct answer...
Other examples from other links did not work either.
Please see How to convert an IPv4 address into a integer in C#?
What you are seeing appears to be an endian problem.
As a generic function, if your IP address is A.B.C.D then the value you're after is:
A << 24 + (= A * 16777216)
B << 16 + (= B * 65536)
C << 8 + (= C * 256)
D
On little endian machines when the four-byte array ABCD is cast into an integer it comes out with A as the least significant byte instead of the most significant.
I don't write vb.net code, but it should be pretty trivial to knock out a function that'll do this.
You'll need to ensure that A - D are all in the 0 .. 255 range first, though!
How to convert an IPv4 address into a integer in C#?
example code is listed in the picked answer
e; f, b
This might work, will try it and see.
public double IPAddressToNumber(string IPaddress)
{
int i;
string [] arrDec;
double num = 0;
if (IPaddress == "")
{
return 0;
}
else
{
arrDec = IPaddress.Split('.');
for(i = arrDec.Length - 1; i >= 0 ; i = i -1)
{
num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
}
return num;
}
}